Javascript get text from element

.text Content

Считываем и записываем текстовое содержимое элемента.

Время чтения: меньше 5 мин

Кратко

Скопировать ссылку «Кратко» Скопировано

Свойство text Content позволяет считывать или задавать текстовое содержимое элемента. Обращение к свойству вернёт строку, которая будет состоять из текстового содержимого всех вложенных элементов, даже если они скрыты с помощью CSS и не видны на экране.

Аналогичной функциональностью, но с некоторыми ограничениями обладает свойство inner Text . Оно работает так же, но не включает в себя скрытые элементы.

Пример

Скопировать ссылку «Пример» Скопировано

   

Заголовок

И параграф полезного текста

section> h1>Заголовокh1> p>И параграф полезного текстаp> section>

Обращение к свойству text Content тега весь текст внутри элемента:

 const section = document.querySelector('section')console.log(section.textContent)// ЗаголовокИ параграф полезного текста const heading = document.querySelector('h1')heading.textContent = 'Новый заголовок'// В результате будет: 

Новый заголовок

const section = document.querySelector('section') console.log(section.textContent) // ЗаголовокИ параграф полезного текста const heading = document.querySelector('h1') heading.textContent = 'Новый заголовок' // В результате будет:

Новый заголовок

Как понять

Скопировать ссылку «Как понять» Скопировано

Для считывания и изменения текстового содержимого браузер предоставляет свойства inner Text и text Content . Запись значения работает идентично для обоих. Значение, которое возвращается при чтении свойств отличается. text Content возвращает строку с содержимым всех вложенных потомков, вне зависимости от того, скрыты они или нет. inner Text же возвращает содержимое только видимых элементов.

Свойство может изменить только текстовое содержимое элемента, потому если присвоить строку, содержащую HTML, то она вставится как простой текст и не превратится в реальные DOM-элементы. Для того чтобы вставлять HTML c помощью строки подойдёт свойство inner H T M L .

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Обращение к свойству text Content вернёт текстовое содержимое элемента. Если внутри элемента находятся дочерние узлы, то результат будет являться конкатенацией вызовов text Content для всех этих узлов.

   

Заголовок

Параграф

Второй параграф

div> h1>Заголовокh1> p>Параграфp> p>Второй параграфp> div>
 const element = document.querySelector('div') console.log(element.textContent)// "ЗаголовокПараграфВторой параграф"// Так как слова не содержат пробелов, то и в итоговой строке между словами их тоже не будет const element = document.querySelector('div') console.log(element.textContent) // "ЗаголовокПараграфВторой параграф" // Так как слова не содержат пробелов, то и в итоговой строке между словами их тоже не будет      

Чтобы изменить текст в элементе нужно присвоить новое значение в свойство text Content .

Установка нового текста с помощью text Content полностью удалит всё старое содержимое и запишет новое текстовое значение. Если внутри элемента были другие вложенные потомки, то все они удалятся.

   

Заголовок

Параграф

Второй параграф

div> h1>Заголовокh1> p>Параграфp> p>Второй параграфp> div>
 const element = document.querySelector('div')element.textContent = 'Я буду единственным текстом здесь' const element = document.querySelector('div') element.textContent = 'Я буду единственным текстом здесь'      

Больше никакой иконки внутри, только новый текст:

   Я буду единственным текстом здесь  div> Я буду единственным текстом здесь div>      

Источник

Node: textContent property

The textContent property of the Node interface represents the text content of the node and its descendants.

Note: textContent and HTMLElement.innerText are easily confused, but the two properties are different in important ways.

Value

A string, or null . Its value depends on the situation:

    If the node is a document or a doctype, textContent returns null .

Note: To get all of the text and CDATA data for the whole document, use document.documentElement.textContent .

Warning: Setting textContent on a node removes all of the node’s children and replaces them with a single text node with the given string value.

Differences from innerText

Don’t get confused by the differences between Node.textContent and HTMLElement.innerText . Although the names seem similar, there are important differences:

  • textContent gets the content of all elements, including and elements. In contrast, innerText only shows «human-readable» elements.
  • textContent returns every element in the node. In contrast, innerText is aware of styling and won’t return the text of «hidden» elements.
    • Moreover, since innerText takes CSS styles into account, reading the value of innerText triggers a reflow to ensure up-to-date computed styles. (Reflows can be computationally expensive, and thus should be avoided when possible.)

    Differences from innerHTML

    Element.innerHTML returns HTML, as its name indicates. Sometimes people use innerHTML to retrieve or write text inside an element, but textContent has better performance because its value is not parsed as HTML.

    Moreover, using textContent can prevent XSS attacks.

    Examples

    Start with this HTML fragment.

    div id="divA">This is span>somespan> text!div> 

    You can use textContent to get the element’s text content:

    let text = document.getElementById("divA").textContent; // The text variable is now: 'This is some text!' 

    If you prefer to set the element’s text content, you can do:

    .getElementById("divA").textContent = "This text is different!"; // The HTML for divA is now: // 
    This text is different!

    Specifications

    Browser compatibility

    BCD tables only load in the browser

    See also

    Found a content problem with this page?

    This page was last modified on Apr 7, 2023 by MDN contributors.

    Your blueprint for a better internet.

    MDN

    Support

    Our communities

    Developers

    Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
    Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

    Источник

    Javascript get text from element

    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.

    Источник

    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 div style heights
Оцените статью