skip to Main Content

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


  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>
    Login or Signup to reply.
  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>
    Login or Signup to reply.
  3. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search