【问题标题】:how do I select first p tag from html that is a string?如何从作为字符串的 html 中选择第一个 p 标签?
【发布时间】:2020-01-20 08:20:37
【问题描述】:

我正在从无头 CMS 中获取内容,并以字符串形式获取内容,例如:

<div>
  <p>1st p tag</p>
  <p>2nd p tag</p>
</div>

如何选择第一个 p 标签,这样我就可以拥有这样的东西:

const firstPtagContent = "1st p tag"

【问题讨论】:

  • document.querySelector('p') 将选择第一个 p ... 而 .textContent 将是其文本内容

标签: javascript html selectors-api


【解决方案1】:

您可以使用DOMParser 解析字符串并使用querySelector 获取第一个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
)

【讨论】:

    【解决方案2】:

    这样的事情会起作用:

    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>

    【讨论】:

      【解决方案3】:

      你可以使用下面的sn-p。

      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>

      【讨论】:

        【解决方案4】:

        你可以试试这样的:

        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
        )

        【讨论】:

          猜你喜欢
          • 2011-06-10
          • 1970-01-01
          • 2012-01-20
          • 2013-07-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-29
          相关资源
          最近更新 更多