Mayuresh Deshmukh
Mayuresh Deshmukh

Reputation: 27

How i can store all content from <p> tag in array using javascript and jquery?

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']

Upvotes: 0

Views: 550

Answers (3)

Ashkan_Noori
Ashkan_Noori

Reputation: 25

Try this :

var all=$('p');
var len_all=$('p').length;
var all_array=[];
for (var i=0; i < len_all; i++) {
  console.log(all[i].text());
  all_array.push(all[i].text());
}
console.log(all_array)

Or

var all=$('p');
var len_all=$('p').length;
var all_array=[];
for (var i=0; i < len_all; i++) {
  console.log($(all[i]).text());
  all_array.push($(all[i]).text());
}
console.log(all_array)

Upvotes: 0

Mina
Mina

Reputation: 17604

That's because the $('p').text(); will get the text of all p elements.

You can achieve your goal with one line of vanilla javascript, to get all p elements by querySelectorAll and map to get each element textContent

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<p>I am out</p>
<p>I am in</p>
<script>
let all_array = [...document.querySelectorAll('p')].map(el => el.textContent);
console.log(all_array)
</script>
</body>
</html>

Upvotes: 2

David
David

Reputation: 219127

You're getting all of the values as one big value here:

var all=$('p').text();

And then repeatedly pushing that same value into an array:

all_array.push(all);

Instead, loop over the <p> elements and push each value to the array:

var pElements = $('p');
var result = [];
pElements.each(function (i, el) {
  result.push($(el).text());
});
console.log(result);
<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>

Upvotes: 1

Related Questions