'DOM/Javascript: get text after tag
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:
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.
Solution 1:[1]
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>
Solution 2:[2]
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)?
Solution 3:[3]
You can use lastChild and textContent to get it: http://jsfiddle.net/M3vjR/
Solution 4:[4]
Well if you use jQuery there is a sneaky way to get this
x = $("<p><a>hello</a>there</p>")x.contents()[1]
Solution 5:[5]
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.
Solution 6:[6]
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);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | kinakuta |
| Solution 4 | Jibi Abraham |
| Solution 5 | Zon |
| Solution 6 | Kunal Vashist |
