Alerting only text of a specific element

3

I have this code:

<div id="div">
  This is some text.<br/>
  <button>Button</button>
</div>
<script>
  alert(document.getElementById("div").innerText);
</script>

And when I ask to alert the text of #div , it alerts the button text too.

I know that this is not a bug and that it was supposed to happen, but does it have a method to only alert the text of #div without including the button text?

    
asked by anonymous 16.09.2017 / 19:28

1 answer

5

You have to use node (s), you can not go by Elements because this text is inside the element at the same level as button . But using node you can already. For example, .firstChild gives you the first node and .textContent the content.

<div id="div">
  This is some text.<br/>
  <button>Button</button>
</div>
<script>
  alert(document.getElementById("div").firstChild.textContent);
</script>
    
16.09.2017 / 19:30