Troyer
Troyer

Reputation: 7013

Create array with tags on jQuery

I want to get all the "p" from body and create one array, then use this array to print the text content of every one "p", how can I archive it? Very novice question but i'm stuck.

Thank you.

Upvotes: 0

Views: 932

Answers (2)

Indy
Indy

Reputation: 4957

There is plenty method to do it, wheater using pure JavaScript or jQuery:

JavaScript:

var p = document.getElementsByTagName('p'); // Get all paragraphs (it's fastest way by using getElementsByTagName)
var pTexts = []; // Define an array which will contain text from paragraphs


// Loop through paragraphs array

for (var i = 0, l = p.length; i < l; i++) {
    pTexts.push(p[i].textContent); // add text to the array
}

Loop jQuery way:

$.each(p, function(i, el) {
    pTexts.push(el.textContent);

    // or using jQuery text(), pretty much the same as above
    // pTexts.push( $(el).text() );
});

Upvotes: 1

Sudharsan S
Sudharsan S

Reputation: 15393

Try with .map() in jquery

var result = $("body").find("p").map(function() {
   return $(this).text();
}).get();

 console.log(result);

Fiddle

Upvotes: 2

Related Questions