Question:
In a webpage, I need to update the text of an element without altering its child elements. Here's an example HTML structure:
<div> **text to change** <someChild> text that should not change </someChild> <someChild> text that should not change </someChild> </div>
As a jQuery novice, I seek a way to accomplish this task.
Answer:
Mark has provided an excellent solution using jQuery. However, regular JavaScript offers an alternative approach:
JavaScript provides the childNodes property to obtain all child nodes of an element, including text nodes. If the text to be modified consistently appears as the initial child of an element, you can utilize the following code:
var your_div = document.getElementById("your_div"); var text_to_change = your_div.childNodes[0]; text_to_change.nodeValue = "new text";
In this example, we assume that the text to be modified is the first node within the
var your_div = $("your_div").get(0);
The above is the detailed content of How to Modify Parent Element Text in jQuery Without Affecting Child Elements?. For more information, please follow other related articles on the PHP Chinese website!