0

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.

2 Answers 2

2

Try with .map() in jquery

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

 console.log(result);

Fiddle

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

Comments

1

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() );
});

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.