0

Let's say we have following this:

<p class="first">This is paragraph 1.</p> 
<p class="second">This is paragraph 2.</p> 
<p id="third">This is paragraph 3.</p>
<p>This is paragraph 4.</p>

We can save the value of an element in value variable and show like this.

var value = $('p').slice(3,4);
value.text(); // result --> This is paragraph 4

Above way has no problem if we know the number of element but we'll get problem if we have a lot of elements and we want to do with looping. why I get error if I do like this?

$('p')[3].text();

What should I do if I want to loop and get values?

4 Answers 4

2

Loop like this:

$('p').each(function(i) {
  alert($(this).text());
  //or this:
  alert($('p').eq(i).text());
});

When you do [3] you're getting the DOM element <p> not the jQuery object, which has the .text() method.

$('p')[3] == DOM Element, doesn't have `.text()`
$('p').eq(3) == jQuery object, has `.text()`
Sign up to request clarification or add additional context in comments.

Comments

1

jQuery objects can function as arrays of DOM elements, not other jQuery objects.
Therefore, writing $(...)[3] gives you a raw DOM element, not a jQuery object.

You need to call the eq function:

$('p').eq(3).text();

Comments

1

The problem with what you're trying to do is that $('p')[3] will not return a jQuery object, and therefore it does not have a text() function.

Instead, use something like this:

$('p.eq(3)')

// OR

$('p').eq(3)

A general rule of thumb is that if you aren't sure whether or not an object has any jQuery methods, you're probably well off simply wrapping it in $(...) or jQuery(...), the latter being used more if you are using jQuery.noConflict(); (and therefore using Prototype or some other library that uses $ as its variable).

Comments

1

The reason for your error is that you get the actual DOM element when you get it using array notation. The DOM element doesn't have a text() function. To get all the values, use each.

var values = [];
$('p').each( function(i) {
    values[i] = $(this).text();
}

To get a particular element, use eq();

var value = $('p').eq(3).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.