0

Using JavaScript, how can I access text located in the DOM but not wrapped in tags by itself.

For example:

<div class="container">
  <a href="home.html">Home</a> |
  <a href="abou.html">About</a> |
  <a href="cont.html">Contact</a> |
  <a href="misc.html">Misc.</a>
  CopyrightNot @ 2016
</div>

How can I select "CopyrightNot @ 2016"?

bloodyKnuckles
  • 11,551
  • 3
  • 29
  • 37

1 Answers1

1

If the text you want to access with JavaScript is always after all the tags also in wrapped in the div.container tag, then use this:

document.querySelector('div.container').lastChild.textContent.trim()

Use the querySelector method to access the div.container element, then access the lastChild property on that element, which gives you the textNode you're looking for. Now just get the text on that element using the textContent property, and finally use the trim method to get rid of the leading and trailing spaces and line returns.

JSBin example.


Likewise, if it's before all the other tags, use firstChild:

document.querySelector('div.container').firstChild.textContent.trim()

And you can access ALL the child nodes, tags and text, within the div.container element using the childNodes array.

// for loop
var con = document.querySelector('div.container');
for ( ii = 0, len = con.childNodes.length; ii < len; ii += 1 ) {
  console.log(con.childNodes[ii].textContent.trim());
}

If you know the position the text is located within the tags, such as third postion, then it's index will be 2 and you can access the text with:

document.querySelector('div.container').childNodes[2].textContent.trim()

bloodyKnuckles
  • 11,551
  • 3
  • 29
  • 37