Reputation: 110
I need to add this <div><a href="">Test</a>and another <a href="">Test</a></div>
text to array like this: ['Test', 'and another', 'Test']
, but the result is ['Test', 'Test']
, 'and another' text is ignored.
let text = [];
$('div').children().each(function () {
text.push($(this).text());
});
Upvotes: 0
Views: 997
Reputation: 4360
Use .contents() instead of .children(). children() function does not include comments and text node. So your function would be:
let text = [];
$('div').contents().each(function () {
text.push($(this).text());
});
Upvotes: 1
Reputation: 1323
as it is explained here
.children() only return html elements and not texts so it is obvious that and another is not included in the items. in order to achieve your desired result you can simply put it in <span>
tag :)
Upvotes: 2
Reputation: 11975
You can do it with just pure Javascript, no need Jquery.
Using .childNodes and .textContent:
var text = [];
document.querySelector('div').childNodes.forEach((el) => {
text.push(el.textContent)
})
console.log(text)
<div><a href="">Test</a>and another <a href="">Test</a></div>
Upvotes: 1