0

How can I modify the css of an object when iterating through an array of objects? Here's my attempt:

var buttons = $('#nav li');
for(button in buttons){
    button.css("opacity","1");
}

But this gives the error:

Uncaught TypeError: Object 0 has no method 'css'
(anonymous function) 
k jquery-1.8.0.min.js:2
l.fireWith jquery-1.8.0.min.js:2
p.extend.ready jquery-1.8.0.min.js:2
D
4
  • 1
    button is set to the keys of the object or array, not the values -- JS for-in is not like PHP foreach. Commented Sep 20, 2013 at 23:52
  • ahh, that's why! $(buttons[button]).css("opacity","1"); works, thank you! Commented Sep 20, 2013 at 23:57
  • But the answer from undefined is the idiomatic way to iterate through a jQuery collection. Commented Sep 20, 2013 at 23:59
  • yeah, will be using that instead! Commented Sep 21, 2013 at 0:02

1 Answer 1

1

You don't have to iterate through the collection for setting css, jQuery does this for you:

$('#nav li').css('opacity','1');

You are calling the .css() method on all the keys of the jQuery object and not on the actual selected elements, jQuery returns a jQuery-wrapped array of selected elements, if you want to get the actual array of the elements, you can use .get() method and If you want to iterate through the collection, you can simply use the .each() method:

$('#nav li').each(function(index, element) {
   // ...
});
Sign up to request clarification or add additional context in comments.

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.