Following is the code i am working on
var all=$('p').text();
var len_all=$('p').length;
var all_array=[];
for (var i=0; i < len_all; i++) {
console.log(all);
all_array.push(all);
}
console.log(all_array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p>I am out</p>
<p>I am in</p>
I want all the <p>
tag contents in var all_array=[];
I am getting following output in console:
(2) [‘I am outI am in’, ‘I am outI am in’]
Expected is:
[‘I am out’,’I am in’]
3
Answers
You’re getting all of the values as one big value here:
And then repeatedly pushing that same value into an array:
Instead, loop over the
<p>
elements and push each value to the array:That’s because the
$('p').text();
will get thetext
of allp
elements.You can achieve your goal with one line of
vanilla javascript
, to get allp
elements byquerySelectorAll
andmap
to get each elementtextContent
Try this :
Or