Selecting the first-level text element '.text()' without selecting child elements
I have the following html
<label>
outer
<span>inner</span>
</label>
I want to replace the 'outer' value, leaving the span with its 'inner' text intact. Using
$('label').text('new outer开发者_如何学编程');
replaces the entire content of the label (along with the span). Is there a nifty way to only select the text block 'outer' without adding extra spans or doing advanced stuff like storing the value of the label's inner span and then reapplying it?
This will update just the text of the first Text
node in the element, without disturbing the span
(or any subsequent Text
nodes):
$("label").contents().each(function() {
// Within this iterator function, jQuery sets `this` to be
// each child node (including Text nodes, not just Elements)
if (this.nodeType === 3) { // 3 = text node
this.nodeValue = "updated ";
return false;
}
});
Live example | source
And of course, you can refine that. The Text
node's current text is available (of course) from node.nodeValue
, so if you wanted to just modify that (perhaps replacing only certain parts of it), you can do that; or if you wanted to modify the first one that matched a given pattern, etc.
Is there a nifty way to only select the text block 'outer' without adding extra spans or doing advanced stuff like storing the value of the label's inner span and then reapplying it?
Not really.
You could use a regular expression to replace everything before <span>
, but it would be a clunky regex, and while it would work for some cases, it would break if you had any other markup in there, especially if you had another element wrapping the <span>
.
My suggestion would be to simply put another span in there. If you know you're going to be manipulating that block of code, then give it an element in the DOM. That's the best way to make it easy to get at, and it gets you away from doing silly stuff like rebuilding the whole structure just because you wanted to change a single word.
精彩评论