I am trying to get and array of text after using the text function, having a ul list like
<ul>
<li>one
<ul>
<li>one one</li>
<li>one two</li>
</ul>
</li>
</ul>
then get something like
['one', 'one one', 'one two']
I am trying to get and array of text after using the text function, having a ul list like
<ul>
<li>one
<ul>
<li>one one</li>
<li>one two</li>
</ul>
</li>
</ul>
then get something like
['one', 'one one', 'one two']
var array = $('li').map(function(){
return $.trim($(this).text());
}).get();
Demo Fiddle --> http://jsfiddle.net/EC4yq/
.toArray().get() method do? BTW We can do $('li').toArray().map((li) => { return li.innerText.trim(); })Several of the answers ignore the OP's desired format.
This will give you what you want.
$('li').map(function(){
var $clone = $(this).clone();
$clone.children('*').remove();
return $.trim($clone.text());
}).get()
Fiddle: http://jsfiddle.net/pE9PR/
The accepted answer actually not answer the question, OP want firstChild text
['one', 'one one', 'one two']
but accepted answer give textContent
['one\n\none one\none two', 'one one', 'one two']
There are two method to answer, first using jQuery contents()
var array = $('li').map(function() {
return $(this).contents()[0].textContent.trim()
}).get();
console.log(array)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>one
<ul>
<li>one one</li>
<li>one two</li>
</ul>
</li>
</ul>
second, using plain js firstChild
var array = Array.from(document.querySelectorAll('li'))
.map(i => i.firstChild.textContent.trim())
console.log(array)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>one
<ul>
<li>one one</li>
<li>one two</li>
</ul>
</li>
</ul>