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.
You can target the br element and use . get(index) to fetch the underlying DOM element, the use nextSibling to target the text node. Then nodeValue property can be used to get the text.
The textContent is the DOM property that is used to set text content for the HTML element or get the text content written inside that element. If you set the text using textContent for an element, then the other child elements will be removed and only this text will be added in that element.
textContents is all text contained by an element and all its children that are for formatting purposes only. innerText returns all text contained by an element and all its child elements. innerHtml returns all text, including html tags, that is contained by an element.
To add text to the <p> element, you must create a text node first. This code creates a text node: const node = document. createTextNode("This is a new paragraph.");
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With