Home >Web Front-end >JS Tutorial >How to Modify Parent Element Text in jQuery Without Affecting Child Elements?

How to Modify Parent Element Text in jQuery Without Affecting Child Elements?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-26 21:41:12692browse

How to Modify Parent Element Text in jQuery Without Affecting Child Elements?

Modifying Element Text Without Affecting Child Elements Using jQuery

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

element. You can still leverage jQuery to select the
element, in which case:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn