I'm fetching content from a headless CMS and I get content as a string like:
<div>
<p>1st p tag</p>
<p>2nd p tag</p>
</div>
how do I select the 1st p tag so I can have something like this:
const firstPtagContent = "1st p tag"
You can parse the string using DOMParser
and use querySelector
to get the first p
const str = `<div> <p>1st p tag</p> <p>2nd p tag</p> </div>` let doc = new DOMParser().parseFromString(str, 'text/html') console.log( doc.querySelector('p').textContent )
Something like this would work:
var firstParagraph = document.getElementById('container').getElementsByTagName('p')[0] console.log(firstParagraph.textContent)
<div id="container"> <p>1st p element</p> <p>2st p element</p> </div>
You can use below snippet.
var firstParagraph = document.getElementById('container').getElementsByTagName('p')[0] console.log(firstParagraph.textContent)
p { outline: dotted red } /* Just to show the widths */
<div id="container"> <p>1st p tag</p> <p>2nd p tag</p> </div>
You may try something like this:
const str = `<div> <p>1st p tag</p> <p>2nd p tag</p> </div>` let doc = new DOMParser().parseFromString(str, 'text/html') console.log( doc.querySelector('p').textContent )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.