Reputation: 7013
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
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
Reputation: 15393
Try with .map()
in jquery
var result = $("body").find("p").map(function() {
return $(this).text();
}).get();
console.log(result);
Upvotes: 2