Is there a way to get innerText of only the top element (and ignore the child element's innerText)?
Just iterate over the 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("");
This will work in your example:
document.getElementById("item").firstChild.nodeValue;
Note: Keep in mind that this will work if you know you are dealing with that specific HTML. If your HTML can change, for example to:
<div>
<div class="item"> child node text </div>
top node text
</div>
then you should use the more generic solution by @Tim Down
Here is working code snippet:
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>
- Clone the element.
- Loop through all child nodes (backwards, to avoid conflicts):
If the element has atagName
attribute, then it's an element: Remove the node. - Use
innerText
to get the textual contents (with fallback totextContent
, wheninnerText
is not supported).
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'];