Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery index on each function

I am curious why I need this index

$(document).ready(function() {
        $(".divToggle").each(function(index){
            var buttonId = $(this)[0].attributes["id"].value.toString();
            var idParts = buttonId.split('_');
            var uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";             
            $(this).click(function() {
                 $("#" + uniquePart).toggle("slow");
            });            
        });
    });

Why do I need the "[0]" in "var buttonId = $(this)[0]…" Without it, I get an attributes["id"] is null error..

like image 400
esastincy Avatar asked Feb 16 '26 13:02

esastincy


2 Answers

Use this instead

var buttonId = this.id;

or jQuery way

var buttonId = $(this).attr("id");
like image 149
Sang Suantak Avatar answered Feb 19 '26 04:02

Sang Suantak


with $(this) you are still in the jquery model where the correct way to get id is .attr("id")

writing $(this)[0] drops you back into the DOM model where its as you wrote.

like image 34
Matt Avatar answered Feb 19 '26 03:02

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!