Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

html - Using jQuery, how to modify text outside of tags?

Given a string of text that is both adjacent to a span and inside of a div, what are some methods to modify just that text, leaving the surrounding HTML intact? For example:

<div id="my-div">modify this text<span id="my-span"></span></div>

I have tried things like

$('#my-div').html(function(i, elem){blah;});

but this seems to cause the span to be deleted and a new span to be added (I notice that some styling is lost on the span).

I realize that it would be best to wrap the text string in its own HTML tags before applying client-side code, but that is out of my control.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This seems to work:

$('#my-div').contents()
            .filter(function() { return this.nodeType == 3; })
            .replaceWith('new text or html');

nodeType == 3 is to test for a text node.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...