Reputation: 17
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/
Upvotes: 0
Views: 882
Reputation: 5708
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>
Upvotes: 0
Reputation: 370619
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>
Upvotes: 2