Home > Web Front-end > JS Tutorial > How to Extract Text Node Content from an HTML Element in JavaScript?

How to Extract Text Node Content from an HTML Element in JavaScript?

Barbara Streisand
Release: 2024-12-01 19:41:15
Original
562 people have browsed it

How to Extract Text Node Content from an HTML Element in JavaScript?

Getting the Text Node of an Element

When working with HTML elements in JavaScript, it's often necessary to obtain the text content within those elements. However, elements can contain various types of nodes, including text nodes, comment nodes, and element nodes. This article explores a cross-browser solution for retrieving the text node.

Consider the following HTML:

<div class="title">
   I am text node
   <a class="edit">Edit</a>
</div>
Copy after login

Our goal is to obtain the "I am text node" content while preserving the "Edit" link.

To accomplish this, we can utilize jQuery's contents() and filter() functions:

var text = $(".title").contents().filter(function() {
  return this.nodeType == Node.TEXT_NODE;
}).text();
Copy after login

This code selects the element with the class "title" and obtains its contents. Then, it applies a filter function to the contents, selecting only nodes with a nodeType of Node.TEXT_NODE (i.e., text nodes). Finally, it extracts the text content from the filtered result.

Using this approach, we can successfully retrieve the desired text node content without removing the "Edit" tag.

The above is the detailed content of How to Extract Text Node Content from an HTML Element in JavaScript?. 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