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 mod开发者_如何转开发ify 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.
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.
What about using jQuery's contents()
method?
http://api.jquery.com/contents/
have you tried something like:
$(document).ready(function(){
var elems = $('#myDiv *').detach();
$('#myDiv').text('new texts...').append(elems);
})
quick demo
edit
or as alex suggested to use .contents()
:
$('#myDiv').contents()
.filter(function(){
return this.nodeType != 1 && $.trim($(this).text()) != '';
})
.replaceWith("I am the new text");
Instead of modifying its HTML string, modify its DOM tree, find the top-level text nodes and do with them.
You could just use string replace:
HTML
<div id="my-div">modify this text <span id="my-span">or this text here</span></div>
Script
$('#my-div').html(function(i,html){
return html.replace('this text', 'some new text').replace('or this text', 'and replace this text');
})
精彩评论