Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Array of Elements' Strings

From the given HTML, I am trying to extract the pText array, so that I end up with two <p> items (in this case), from which I can extract the two text strings "link test1" and "link test2", and pop an alert for each of them. Why doesn't the below script work?

HTML:

<div>
    <p><a href='/'>link</a> test1</p>
    <p><a href='/'>link</a> test2</p>
</div>

Javascript:

var pText = $('div').find('p');

for (i = 0; i < pText.length; i++) {
    alert(pText[i].text());
}
like image 898
Guessed Avatar asked Jun 21 '26 05:06

Guessed


1 Answers

Since that you're using jQuery, if you want to use the .text() method you have to extract a jQuery object and use .eq(i) instead of [i], which returns a normal element.

Here's the correct code:

var pText = $('div').find('p');

for (i = 0; i < pText.length; i++) {
    alert(pText.eq(i).text());
}

Also, you can simplify your code using the .each() method (instead of the for loop), which calls a given function for every element of your jQuery collection (pText). In my opinion, it's easier, here you go:

var pText = $('div').find('p');

pText.each(function(i, el) {
    alert($(el).text());
});
like image 125
Marco Bonelli Avatar answered Jun 22 '26 17:06

Marco Bonelli