简体   繁体   中英

get element text without child content in javascript

I have below html:

<span id='User_span'>whatup <span>man</span> big guy</span>

I just want to get the content of User_span without it's child or in other word, I just want to get what up big guy .

tried $('#User_span').text(); but that also get the child text as well.

I don't mind javascript or jquery.

Test: https://jsfiddle.net/mn9chyst/3/

Take all the child nodes of the span which are text nodes and concatenate them together. No need for a big library like jQuery for something so trivial:

 const { childNodes } = document.querySelector('#User_span'); const result = [...childNodes].filter(node => node.nodeType === 3).map(node => node.textContent).join(''); console.log(result);
 <span id='User_span'>whatup <span>man</span> big guy</span>

You can also use the .reduce() method like this:

 // transform the childNodes HTMLCollection object into an array var children = [...document.getElementById('User_span').childNodes]; //.nodeType === 3 means text node var result = children.reduce((acc, el) => { return acc + (el.nodeType === 3? el.textContent: ''); }, ''); console.log(result);
 <span id='User_span'>whatup <span>man</span> big guy</span>

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