Evita Urbanoviča
Evita Urbanoviča

Reputation: 110

add div text to array

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

Answers (3)

Mustafa sabir
Mustafa sabir

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());
});

Ref Link

Fiddle

Upvotes: 1

Mahyar Mottaghi Zadeh
Mahyar Mottaghi Zadeh

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

Cuong Le Ngoc
Cuong Le Ngoc

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

Related Questions