0

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?

2
  • Wouldn’t that be just console.log(Array.from(document.querySelectorAll(".planet"), ({textContent}) => textContent)); — without jQuery? Commented Jun 14, 2018 at 5:25
  • @Xufox thanks, didn't realise Array.from supported a mapping function Commented Jun 14, 2018 at 5:30

4 Answers 4

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

0

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>

Comments

0

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>

3 Comments

what is the purpose of i, e arguments in your example ?
@puerto - Nothing over here they are not required. Though i means the index and e means the element.
@puerto - I have updated the answer. See I can use e in place of this for getting values. Hope it clarifies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.