Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript get textContent excluding children

First, I'm creating a library for JavaScript and I can not use jQuery. I'm trying to get the text content of an HTML element without the text contents of its children.

Both attributes innerText and textContent don't give me what needed, please help.

like image 401
Dee Avatar asked Mar 26 '16 05:03

Dee


People also ask

How do you check if a div has child or not?

To check if an HTML element has child nodes, you can use the hasChildNodes() method. This method returns true if the specified node has any child nodes, otherwise false .

Should I use textContent or innerText?

textContent gets the content of all elements, including <script> and <style> 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.

What is the difference between textContent and innerHtml?

textContents is all text contained by an element and all its children that are for formatting purposes only. innerText returns all text contained by an element and all its child elements. innerHtml returns all text, including html tags, that is contained by an element.

How do I select a specific child in JavaScript?

Given an HTML document and the task is to select a particular element and get all the child elements of the parent element with the help of JavaScript. For this, there are 2 ways to get the child element: By using the children property. By using querySelector Method.


2 Answers

You can solve using DOM API as childNodes and nodeType.

var elChildNode = document.querySelector("#hello").childNodes;
var sChildTextSum = "";

elChildNode.forEach(function(value){
    if(value.nodeType === Node.TEXT_NODE) { 
        console.log("Current textNode value is : ", value.nodeValue.trim());
        sChildTextSum += value.nodeValue;
    }
}); 

console.log("All text value of firstChild : ", sChildTextSum);

I created a sample code as above.

https://jsfiddle.net/nigayo/p7t9bdc3/

like image 197
superui Avatar answered Sep 22 '22 16:09

superui


var mydiv = getElementByID("id");
function Get_text(element) {
    var selected = element.cloneNode(true);
    var text;
    while (selected.firstChild) {
      if (selected.firstChild.nodeType == 3) text = selected.firstChild.nodeValue;
      selected.removeChild(selected.firstChild);
    }
    return text;
  }
Get_text(mydiv);
like image 37
JHON ZEKE Avatar answered Sep 20 '22 16:09

JHON ZEKE