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 firstp
... and.textContent
would be its text content – Jaromanda X Commented Jan 20, 2020 at 8:21
4 Answers
Reset to default 7You 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
版权声明:本文标题:javascript - how do I select first p tag from html that is a string? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744327678a2600807.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论