0

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 3

2

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>

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

Comments

1

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>

Comments

0

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)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.