9

How do I get the text "there" that comes after a tag in an html document:

<p><a>hello</a>there</p>

I see that there is a way to do it with xpath:

Get text from next tag

but I'm not using xpath and am hoping not to have to start just for this. I realize that I can get ALL the text inside the p tag, but I want to get just the "there" text, as well as know its relationship to the p and a tags. It doesn't seem to be anyone's child or sibling. (You can assume that I can get any of the other elements/nodes so it can be relative to those.) Every DOM tutorial seems to ignore the fact that text can occur outside tags.

Thanks.

Community
  • 1
  • 1
user984003
  • 28,050
  • 64
  • 189
  • 285

6 Answers6

8

You can use several ways to get the tag and the text

let p = document.querySelector('p'); // first p on the page
console.log(p.lastChild.textContent)

let ps = document.querySelectorAll('p'); // all p on the page
console.log(ps[0].lastChild.textContent)

// using tagName
p = document.getElementsByTagName('p')[0];
console.log(p.childNodes[1].textContent)
<p><a>hello</a>there</p>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • yes, it really is that simple :) "there" is a child of P. For some reason that wasn't working for me. Thanks. – user984003 Feb 20 '12 at 10:38
5

use this .. http://jsfiddle.net/2Dxy4/

This is your HTML --

<p id="there">
   <a>hello</a>
   there
</p>​

In your JS

alert(document.getElementById("there").lastChild.textContent)​

or

alert(document.getElementById("there").childNodes[1].textContent)​
Vivek Chandra
  • 4,240
  • 9
  • 33
  • 38
0

You can find children tags of your parent tag:

var pTag = ...
var childNodes = pTag.childNodes;

Finally you can find your text in a text node after a node.

Zon
  • 18,610
  • 7
  • 91
  • 99
0

You can use lastChild and textContent to get it: http://jsfiddle.net/M3vjR/

kinakuta
  • 9,029
  • 1
  • 39
  • 48
0

Well if you use jQuery there is a sneaky way to get this

x = $("<p><a>hello</a>there</p>")
x.contents()[1]

Jibi Abraham
  • 4,636
  • 2
  • 31
  • 60
-1

You have to first get the a attribute innerhtml then take total innerhtml with using substring you can have your there part ..

$(document).ready(function () {
var getA=$("p >a").text();
var getA=getA.length;
var takeTotal=$("p").text();
var result=takeTotal.substring(get);
alert(result);
});
Kunal Vashist
  • 2,380
  • 6
  • 30
  • 59