3

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..

6 Answers 6

4

Use this instead

var buttonId = this.id;

or jQuery way

var buttonId = $(this).attr("id");
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2
$(this)[0]

Is doing 2 things -

  1. Getting you the first element in the matched set, as you're looping round a set of results one by one the index is probably redundant in this case
  2. Returning a 'normal' JavaScript DOM object rather than a jQuery wrapped object

Looking at your code I believe you could achieve the same result by doing this -

var buttonId = this.id;

Comments

1
$(".divToggle").each(function(index, element){
    var buttonId = element.id,
        idParts = buttonId.split('_'),
        uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";

    $(element).click(function() {
         $("#" + uniquePart).toggle("slow");
    });            
});

1 Comment

This is a really cool solution, it is actually what I ended up using in my code. thanks
1

try

 var buttonId = $(this).attr("id");

Comments

1

Technically you don't need it with a little modification of your code. What happens with jQuery selectors is they are simply a bunch of element references in an array. so instead of

<div id ="myelement"></div>

you get

[<div id ="myelement"></div>]

using $(this) puts this in an array and allows it to be used with jQuery functions. If you aren't using jQuery functions just use this. So your code would become

var buttonId = this.attributes["id"].value.toString();

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.