【问题标题】:Javascript: is there an elegant way to get the *direct* innerText of a node and no text from descendants? [duplicate]Javascript: is there an elegant way to get the *direct* innerText of a node and no text from descendants? [duplicate]
【发布时间】:2022-12-02 08:46:43
【问题描述】:

I'd like to get thedirecttext content of DOM element, butexcludethe text of any descendant elements.

el.innerText always includes the text of descendants. I wish there were something like el.ownText.

【问题讨论】:

    标签: javascript dom innertext


    【解决方案1】:

    To get the text content of a DOM element without the text of its descendant elements, you can use the textContent property of the element, which returns the text of the element and its direct children, but not the text of its descendants.

    Here is an example:

    const el = document.getElementById('my-element');
    const text = el.textContent;
    

    This will give you the text content of el, but not the text content of any descendant elements of el. If you want to exclude the text content of certain descendant elements, you can use the querySelectorAll method to select those elements and set their textContent property to an empty string.

    For example:

    const el = document.getElementById('my-element');
    const excludedElements = el.querySelectorAll('.excluded-class');
    excludedElements.forEach(e => e.textContent = '');
    const text = el.textContent;
    

    This will set the text content of all descendant elements with the class excluded-class to an empty string, so that they are not included in the final text content of el.

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 2022-07-14
      • 2022-12-26
      • 2022-12-27
      • 2022-12-27
      • 2022-12-01
      • 2022-12-28
      • 2022-12-02
      • 1970-01-01
      相关资源
      最近更新 更多