Is there a way to get innerText of only the top element (and ignore the innerText child)?

Is there a way to get innerText of only the top element (and ignore the innerText child)?

Example:

<div> top node text <div> child node text </div> </div> 

How to get "top node text" while ignoring "child node text"? The innerText property of the top div seems to return the concatenation of both the inner and upper text.

+8
source share
5 answers

Just iterate over child nodes and concatenate text nodes:

 var el = document.getElementById("your_element_id"), child = el.firstChild, texts = []; while (child) { if (child.nodeType == 3) { texts.push(child.data); } child = child.nextSibling; } var text = texts.join(""); 
+11
source
  • Clone an item.
  • Scroll through all the child nodes (back to avoid conflicts):
    If the element has a tagName attribute, then this element is: Remove the node.
  • Use innerText to get text content (returning to textContent when innerText not supported).

the code:

 var elem = document.getElementById('theelement'); elem = elem.cloneNode(true); for (var i=elem.childNodes.length-1; i>=0; i--) { if (elem.childNodes[i].tagName) elem.removeChild(elem.childNodes[i]); } var innerText = elem['innerText' in elem ? 'innerText' : 'textContent']; 
+4
source

This will work in your example: document.getElementById("item").firstChild.nodeValue;

Note. Keep in mind that this will work if you know that you are dealing with this particular HTML. If your HTML may change, for example:

 <div> <div class="item"> child node text </div> top node text </div> 

then you should use the more general @Tim Down solution


Here is a snippet of working code:

 window.onload = function() { var text = document.getElementById("item").firstChild.nodeValue; document.getElementById("result").innerText = text.trim(); }; 
 #result { border: 1px solid red; } 
 <div id="item"> top node text <div> child node text </div> </div> <strong>Result:</strong> <div id="result"></div> 
+3
source

If you do not want to ignore the inner text of the child, use the following function:

 function getInnerText(el) { var x = []; var child = el.firstChild; while (child) { if (child.nodeType == 3) { x.push(child.nodeValue); } else if (child.nodeType == 1) { var ii = getInnerText(child); if (ii.length > 0) x.push(ii); } child = child.nextSibling; } return x.join(" "); } 
0
source

 function getDirectInnerText(element) { var childNodes = element.childNodes; result = ''; for (var i = 0; i < childNodes.length; i++) { if(childNodes[i].nodeType == 3) { result += childNodes[i].data; } } return result; } element = document.querySelector("div#element"); console.log(getDirectInnerText(element)) 
 <div id="element"> top node text <div> child node text </div> </div> 
0
source

Source: https://habr.com/ru/post/908767/


All Articles