How to get text around an element?
If I have
<div id='wrapper'>
<fieldset id='fldset'>
<legend>Title</legend>
Body text.
</fieldset>
</div>
How could I retrieve the "Body text" without retrieving the text inside of legend tag?
For instance, if I wanted to see if the text inside the fieldset contains the word "body" and change that word, while ignoring开发者_StackOverflow whatever might be in the legend? innerHTML retrieves all text from all children nodes.
Use of jQuery wouldn't be a problem.
$("#fldset").contents().eq(2).text();
Without a library --
var fldset = document.getElementById("fldset"),
txt = fldset.lastChild.textContent || fldset.lastChild.innerText;
alert(txt);
This will get all the text nodes of fldset
leaving out any other element and it's content:
var fldsetContent = $('#fldset').contents();
var text = '';
$(fldsetContent).each( function(index, item) {
if( item.nodeType == 3 ) text += $.trim($(item).text());
});
alert( text );
Live example
$('#fldset').clone().find('legend').remove().end().text()
But you should also search around the SO
- Using .text() to retrieve only text not nested in child tags
- Clip content with jQuery
I can't think of a way other than
$("#result").html($("#wrapper").text().replace($("legend").text(),""));
but there should be a more elegant way. You can also create a new element as a copy of this one, remove all the children and get text. Hmm... That would be:
var newElement = $("#fldset").clone();
newElement.children().remove();
$("#result").html(newElement.text());
So doesn't matter how many and which type of children node has, this would work. Here: http://www.jsfiddle.net/wFV4c/
To turn all plain text nodes inside the field set red:
jQuery.each($('#fldset').contents(),function(index,value){
if(value.textContent == value.nodeValue){
$(this).wrap('<span style="color:red;" />')
}
});
精彩评论