I tried to use $('selector').text("") to remove a text node from a parent element, and it removed all of the parent's element nodes, too. The text node in question was "floating" between two element nodes, inside the parent element, like the "or" in this example (HTML was generated by a vendor's system):
I did find the correct way to delete only this text node, using $('selector').contents() and then filtering for nodeType === 3, but I would like to understand why my original script, using text() deleted the element nodes.
I've set up a JSFiddle with a script that correctly removes only the text node, and a script that uses text() and removes all child nodes. I'd appreciate some help to correct my misunderstanding of what I expected text() would do here. Thank you.
Answer
That's just how the API was designed, for performance and consistency reasons.
From the jQuery API Documentation:
.text( text )
Returns: jQuery
Description: Set the content of each element in the set of matched elements to the specified text.
Performance-wise, this implementation makes the most sense because it is far less work to leverage the built-in textContent (or innerText, for IE) property of HTML elements (which replace the entire content of the element with a text node as well) than to search through the list of child nodes and update any text nodes that are found.
Consistency-wise, .text(text) is very similar to .html(html), so it makes sense that they would behave in a similar fashion: replacing the entire content of the node with text data or html data, respectively.
No comments:
Post a Comment