2

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?

4 Answers 4

3

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

Comments

0

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

1 Comment

The eq() function may be faster, as I mentioned in my answer.
0

$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();

Comments

-1

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

1 Comment

-1 for being too cumbersome. Use eq as mentioned by other answers.

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.