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());
}
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());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With