2

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());
}
1
  • 1
    $.map($('div p'), function(x) {return $(x).text()}).forEach(alert); Commented Apr 18, 2015 at 22:08

4 Answers 4

7

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());
});
Sign up to request clarification or add additional context in comments.

Comments

4

text() is a function for jQuery objects.

Use it by wrapping your element in $(..)

alert($(pText[i]).text());

And a better way is to use .each()

$('div').find('p').each(function(){
    alert($(this).text());
});

Comments

0

Try using alert(pText.eq(i).text()); instead of alert(pText[i].text());

The jQuery code will be

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

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

Comments

0
$('#x').children('p').each(function() {
    alert($(this).text()); // "this" is the current element in the loop
});

JSFiddle

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.