Home > Web Front-end > JS Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-11-26 21:41:12
Original
616 people have browsed it

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>
Copy after login

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";
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template