Dorukcan Kişin
Dorukcan Kişin

Reputation: 1131

Jquery selector loop

I'm trying to change width of the divs. But $(div#i) is not true. How can i do that?

<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
    var things = new Array();
        things[0] = 13; things[1] = 26; things[2] = 39;

    for(var i=0;i<things.length;i++)
            $(div#i).css("width",things[i]*100);
</script>

</head>

<body>
<div id="0" style=" width: 300px; height:20px; margin-left: 25px; padding-left: 15px; background-color: #900"> </div> <br>
<div id="1" style=" width: 300px; height:20px; margin-left: 25px; padding-left: 15px; background-color: #900"> </div> <br>
<div id="2" style=" width: 300px; height:20px; margin-left: 25px; padding-left: 15px; background-color: #900"> </div>
</body>
</html>

Upvotes: 1

Views: 2238

Answers (2)

loganfsmyth
loganfsmyth

Reputation: 161457

Selectors should be strings, and you don't need the 'div' since ids must be unique. Also, as mentioned in the comments, ids that are strictly numbers are only valid in HTML5, so if you want this to work consistently on old browsers, I would suggest using the data-index method I posted below.

$('#' + i).css("width",things[i]*100);

I'd also use Array literal syntax.

var things = [13, 26, 39];

On the id uniqueness and compatibility front, I'd really recommend you not use id since it isn't really semantically valuable.

Instead of <div id="...", I'd do <div data-index="..." and make use of jQuery's automatic collection iteration for css.

$('[data-index]').css('width', function(){
    return things[$(this).data('index')] * 100);
});

However in reality, if you have a one-one relationship between divs and their indexes in the array, you can also do this, and not need any extra attributes in your HTML.

$('body > div').css('width', function(i){
  return things[i] * 100;
});

Also remember that you will need to wrap all of this in a ready callback, which you aren't doing in your example.

Upvotes: 10

JosephRT
JosephRT

Reputation: 545

Unless I"m missing something, you could just do:

$('#' + i).css("width",things[i]*100);

Because you're calling an ID, which should be unique on the page.

Upvotes: 2

Related Questions