admin管理员组

文章数量:1405563

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"

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"
Share Improve this question edited Jan 20, 2020 at 8:22 Karolis asked Jan 20, 2020 at 8:20 Karolis Karolis 1651 gold badge4 silver badges12 bronze badges 1
  • 3 document.querySelector('p') would select the first p ... and .textContent would be its text content – Jaromanda X Commented Jan 20, 2020 at 8:21
Add a ment  | 

4 Answers 4

Reset to default 7

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
)

本文标签: javascripthow do I select first p tag from html that is a stringStack Overflow