Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM/Javascript: get text after tag

Tags:

javascript

dom

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.

like image 818
user984003 Avatar asked Feb 20 '12 10:02

user984003


People also ask

How do you get text after BR tag?

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.

What is textContent in JavaScript?

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.

What is the difference between textContent and innerHTML?

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.

How do I add text to DOM 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.");


1 Answers

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>
like image 152
mplungjan Avatar answered Sep 24 '22 00:09

mplungjan