简体   繁体   中英

How to get only <p> tag text including <span> tag

<p class="aaa"> aaa <span class="bbb"> bbb </span> </p>

I want to get only text 'aaa'

But document.querySelector('p.aaa').innerText --> 'aaabbb'

How do I get to text only 'aaa'?

Use childNodes and textContent and using trim() to get the text of p only.

Run snippet below.

 let text = document.querySelector('.aaa').childNodes[0].textContent.trim() console.log(text) ///aaa
 <p class="aaa"> aaa <span class="bbb"> bbb </span> </p>

This function will exclude the content for any child HTML elements from the selected element. It will also account for text values before and after child elements.

 function getText(selector) { return Array.from(document.querySelector(selector).childNodes).reduce((text, node) => text + (node.wholeText || ''), ''); } console.log(getText('p.aaa'));
 <p class="aaa"> aaa <span class="bbb"> bbb </span> ccc </p>

document.querySelector('p.aaa').firstChild

Will return the text you are asking for as is. Then you can trim() if need to remove extra spaces you may not need.

But I would also check to see if the value is simple text such as 'aaa' or a tag in case you might have other elements that satisfies the selector but whose first child could be an html element(tag) instead of simple text.

you can use: let text = document.querySelector('.aaa').childNodes[0].textContent.trim()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM