Search code examples
javascripthtmlselectors-api

how do I select first p tag from html that is a string?


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"

Solution

  • 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
    )