Html node get text

HTML DOM Element innerText

The innerText property sets or returns the text content of an element.

Note

When you set the innerText property, all child nodes are removed and replaced by only one new text node.

See Also:

The Differences Between
innerHTML, innerText and textContent

Syntax

Return the text content of an element or node:

Set the text content of an element or node:

Property Value

Return Value

The Differences Between
innerHTML, innerText and textContent

The innerHTML property returns:
The text content of the element, including all spacing and inner HTML tags.
The innerText property returns:
Just the text content of the element and all its children, without CSS hidden text spacing and tags, except and elements.
The textContent property returns:
The text content of the element and all descendaces, with spacing and CSS hidden text, but without tags.
Читайте также:  Admin login templates in html

HTML Example

JavaScript Examples

let text = document.getElementById(«myP»).innerText;

let text = document.getElementById(«myP»).innerHTML;

let text = document.getElementById(«demo»).textContent;

The innerText property returns:
This element has extra spacing and contains a span element.
The innerHTML property returns:
This element has extra spacing and contains a span element.
The textContent property returns:
This element has extra spacing and contains a span element.

Browser Support

element.innerText is supported in all browsers:

Chrome IE Edge Firefox Safari Opera
Yes 10-11 Yes Yes Yes Yes

Источник

Node.textContent

Позволяет задавать или получать текстовое содержимое элемента и его потомков.

Синтаксис

var text = element.textContent; element.textContent = "Это просто текст";

Описание

  • textContent возвращает null, если узел является документом (en-US), типом документа, или его описанием. Для получения всего текста и CDATA-данных во всём документе можно использовать document.documentElement.textContent .
  • Если узел является CDATA, комментарием, инструкцией, или текстовым элементом, textContent возвращает текст внутри узла в виде строки (т.н. nodeValue (en-US)).
  • Для узлов других типов textContent возвращает конкатенацию свойств textContent всех дочерних узлов, исключая комментарии и строки кода. Если узел не имеет дочерних узлов, будет возвращена пустая строка.
  • Установка данного значения удаляет все дочерние узлы и заменяет их единичным текстовым узлом с указанным значением.

Отличие от innerText

element.innerText был введён Internet Explorer-ом. Работает по тому же принципу за небольшими исключениями:

Отличие от innerHTML

innerHTML , как можно понять из его названия, возвращает HTML. Довольно часто innerHTML используется для получения или записи текста в элемент. Тем не менее, вместо него желательно использовать textContent : этот метод потребляет гораздо меньше ресурсов, так как текст парсится как текст, а не HTML. Кроме того, это защищает от XSS атак.

Пример

// Дан следующий фрагмент: // 
Это — просто текст
// Достаём текстовое содержимое: var text = document.getElementById("block").textContent; // В переменной |text| находится: "Это — просто текст". // Меняем текст: document.getElementById("block").textContent = "Это — просто текст"; // Теперь наш фрагмент выглядит так: //
Это — просто текст

Поддержка браузерами

BCD tables only load in the browser

Спецификация

Смотрите также

Found a content problem with this page?

This page was last modified on 7 нояб. 2022 г. by MDN contributors.

Your blueprint for a better internet.

Источник

HTML DOM Element textContent

The textContent property sets or returns the text content of the specified node, and all its descendants.

Note

When you set the textContent property, all child nodes are removed and replaced by only one new text node.

See Also:

The Differences Between
innerHTML, innerText and textContent

Syntax

Return the text content of a node:

Set the text content of a node:

Property Value

Return Value

Type Description
String The text content of the element and all its descendants.
Returns null if the element is a document, a document type, or a notation.

The Differences Between
innerHTML, innerText and textContent

The innerHTML property returns:
The text content of the element, including all spacing and inner HTML tags.
The innerText property returns:
Just the text content of the element and all its children, without CSS hidden text spacing and tags, except and elements.
The textContent property returns:
The text content of the element and all descendaces, with spacing and CSS hidden text, but without tags.

HTML Example

JavaScript Examples

let text = document.getElementById(«myP»).innerText;

let text = document.getElementById(«myP»).innerHTML;

let text = document.getElementById(«demo»).textContent;

The innerText property returns:
This element has extra spacing and contains a span element.
The innerHTML property returns:
This element has extra spacing and contains a span element.
The textContent property returns:
This element has extra spacing and contains a span element.

Browser Support

element.textContent is a DOM Level 3 (2004) feature.

It is fully supported in all modern browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 11

Источник

Html node get text

Last updated: Jan 12, 2023
Reading time · 3 min

banner

# Get the Text of an HTML Element in JavaScript

Use the textContent property to get the text of an HTML element, e.g. const result = element.textContent .

The textContent property will return the text content of the element and its descendants. If the element is empty, an empty string is returned.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div id="container"> One, span style="background-color: salmon">Twospan>, Three div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const container = document.getElementById('container'); // 👇️ One, Two, Three console.log(container.textContent); // 👇️ One, Two, Three console.log(container.innerText);

get text of div

We used the textContent property to get the text content of the div and its descendants.

If the div element were empty, the property would return an empty string.

# Handling leading and trailing spaces when using textContent

You might get leading or trailing spaces when using textContent depending on the structure of your HTML.

If you need to remove any leading or trailing spaces, use the trim() method.

Copied!
const container = document.getElementById('container'); // 👇️ "One, Two, Three" const result = container.textContent.trim();

The String.trim() method removes the leading and trailing whitespace from a string and returns a new string, without modifying the original string.

The trim() method removes all whitespace characters including spaces, tabs and newlines.

# Using textContent vs innerText

The code snippet also showed that we can use the innerText property to get the text content of an element and its descendants.

Copied!
const container = document.getElementById('container'); // 👇️ One, Two, Three const result = container.innerText;

However, there are some important differences between the textContent and innerText properties:

  1. textContent gets the content of all elements, including script and style elements, whereas innerText only gets the content of «human-readable» elements.
  2. innerText is aware of styling and does not return the text of hidden elements, whereas textContent does not take styles into consideration.
  3. using textContent can prevent cross-site scripting attacks.

innerText takes CSS styles into account, so when the property is accessed, a reflow is triggered to ensure the styles are up-to-date.

Reflows can be expensive and should be avoided when possible.

When you use textContent and innerText to set the element’s text content, the element’s child nodes get removed.

When using the textContent and innerText properties to update the text content of the element, the child nodes of the element get replaced with a single text node with the provided string value.

If you need to set an element’s text content, you should use the insertAdjacentText method instead.

Copied!
const container = document.getElementById('container'); // ✅ Update the text content of the element container.insertAdjacentText('beforeend', ', Four'); // ✅ Update the HTML content of the element container.insertAdjacentHTML( 'beforeend', ', Five', );

The insertAdjacentText method doesn’t remove the child nodes of the element it was called on.

The insertAdjacentText method takes the following 2 parameters:

  1. position — the position relative to the element where the text should be inserted. Can be one of the following 4:
  • beforebegin — before the element itself.
  • afterbegin — just inside the element, before its first child.
  • beforeend — just inside the element, after its last child.
  • afterend — after the element itself.
  1. data — the string from which to create a new text node to insert at the given position.

In the example, we added a string inside of the element, after its last child. However, you can pass a different first argument to the method depending on your use case.

The example also shows how to use the insertAdjacentHTML method to insert HTML into the div element.

The insertAdjacentHTML method takes the same first parameter as insertAdjacentText .

Copied!
const container = document.getElementById('container'); // ✅ Update HTML content of element container.insertAdjacentHTML( 'beforeend', ', Five', );

However, note that you shouldn’t use user-generated input without escaping it, because that leads to a cross-site scripting vulnerability.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью