Paris P
Paris P

Reputation: 355

How to access specific object in an array of DOM objects in jQuery?

Ok so I wanna ask a simple jQuery question about arrays of objects.

If I get all elements (for example all paragraphs) from an html page and store them in an array how can I access one of them to do stuff with it?

For example let's say I have this html:

<!DOCTYPE html>
<html>
    <head>
        <title></title> 
    </head>
    <body> 
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
    <button id="myButton">Click here</button>

    <script src="jquery-1.6.2.min.js"></script>
    <script src="script.js"></script>
    </body>
</html>

This is my script.js:

$(document).ready(function(){
    $("#myButton").click(function(){

        var $paragraphs = $("p"); 
        $paragraphs.detach();  //Works fine, removes all elements
        //$paragraphs[0].detach();  //Doesn't work!

    }); 
});

I'm trying to call detach on the first element of the array, so that I can remove the first paragraph but it doesn't seem to work...

Is there any way to access the first paragraph without using id attributes?

Upvotes: 2

Views: 177

Answers (4)

Sushanth --
Sushanth --

Reputation: 55750

Try this

$($paragraphs[0]).detach();

When you pass a index to the jQuery Object List $paragraphs[0] , the object becomes a DOM Object

var $paragraphs = $("p"); 

var domObj = $paragraphs[0];

var jqueryObj = $(domObj);

So you need to wrap it again as a jQuery Object ..

Instead you can use the :eq() selector

var $paragraph = $("p:eq(0)");  // Selects only the first para
                                 // which is a jQuery Object
$paragraph.detach();   // This works too

Upvotes: 0

frabjousB
frabjousB

Reputation: 104

You can use a filter function: $("p").filter(function(index){ if(index==0){ $(this).detach(); } )};

Upvotes: -1

Bennett McElwee
Bennett McElwee

Reputation: 25810

You can use the :eq selector to select the first element:

$("p:eq(0)").detach();

This will detach just the first element.

You could instead use the .eq() function, which may offer better performance:

$("p").eq(0).detach();

Upvotes: 3

Travis J
Travis J

Reputation: 82347

$paragraphs[0] will unwrap the jquery object into the html element which is why you cannot access detach ( a jquery function ).

You should either iterate through the paragraphs, or re-wrap the object. This should work

var detachParagraph = $paragraphs[0];
$(detachParagraph).detach();

Upvotes: 0

Related Questions