Reputation:
I need to create an array from all planet
text:
<div class='planet'>earth</div>
<div class='planet'>sun</div>
<div class='planet'>moon</div>
var planets = JSON.stringify(Array.from($('.planet').text()));
console.log(planets);
In console I need:
["earth","sun","moon"]
Any help?
Upvotes: 0
Views: 202
Reputation: 28475
Use jQuery.each
var planets = [];
$('.planet').each((i, e) => planets.push($(e).text()));
console.log(planets);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='planet'>earth</div>
<div class='planet'>sun</div>
<div class='planet'>moon</div>
Upvotes: 0
Reputation: 1109
Use each function in jquery to traverse all the elements and then push in array.
planets=[]
$('.planet').each(function(){
planets.push($(this).text())
});
console.log(planets);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='planet'>earth</div>
<div class='planet'>sun</div>
<div class='planet'>moon</div>
Upvotes: 0
Reputation: 1578
var arr = [];
document.querySelectorAll('.planet').forEach(elem => {
arr.push(elem.textContent);
});
console.log(arr);
<div class='planet'>earth</div>
<div class='planet'>sun</div>
<div class='planet'>moon</div>
Upvotes: 0
Reputation: 14561
You can simply use document.querySelectorAll
to select all those elements, use Array.from
to get an array, and use Array.prototype.map
to generate an array from it.
console.log(Array.from(document.querySelectorAll(".planet")).map(t => t.innerText));
<div class='planet'>earth</div>
<div class='planet'>sun</div>
<div class='planet'>moon</div>
Upvotes: 1