Reputation: 67
I have a problem selecting the content inside a tag. Here is the example:
<li>aaaa</li>
<li>bbbb</li>
<li>cccc</li>
I want to select the aaaa bbbb cccc
and store them in an array.
If I use document.getElementsByTagName
, it will store the <li></li>
tags as well. How can I just pick the content?
Upvotes: 2
Views: 1052
Reputation: 561
You can iterate over the elements and get the text content
let textArray = Array.from(document.getElementsByTagName('li')).map(function(elem) {
return elem.textContent;
});
console.log(textArray); // ["aaaa", "bbbb", "cccc"]
Using .textContent
instead of .innerHTML
grabs just the text without any tags that may exists with the li
elements
Upvotes: 0
Reputation: 122027
You can use map()
and return just text of each li
with textContent
var li = document.querySelectorAll('li');
var result = Array.from(li).map(function(e) {
return e.textContent;
})
console.log(result)
<ul>
<li>aaaa</li>
<li>bbbb</li>
<li>cccc</li>
</ul>
Upvotes: 3