Alert text only for a specific element

Asked

Viewed 28 times

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 as well.

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

1 answer

5


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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.