1

I'm having some trouble distinguishing why exactly one method works and the other one doesn't. I have a workable solution by using .eq() but wanted to understand properly why I can't call the .css method using the [] notation if it still returns an object?

Here is my test code, tried to figure it out myself:

$('.slider').each(function() {
  var $slides = $('.slide');

  console.log(jQuery.type($slides.eq(1)));
  console.log(jQuery.type($slides[2]));

  $slides.eq(1).css( {color: 'red'} );
  $slides[2].css( {color: 'red'} );
});

console logs tell me that both selectors are returning an object. So why do I get a typeError on the [] notation like it isn't an object?

Appreciate any clarification.

Thanks,

1 Answer 1

3

The array syntax returns an object but if you want to access JQuery functions on it you will need to call $(object) on it, where .eq() returns a JQuery object. For example:

console.log('By eq:', $('button').eq(0).text())
console.log('By Array as a JQuery Object', $( $('button')[0]).text())
try {
  console.log('By Array:', $('button')[0].text())
} catch(e) {
  console.log('You get an exception because the element doens\'t have a  property named text');
  console.log(e);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A button</button>

Sign up to request clarification or add additional context in comments.

2 Comments

also note that "object" is the most generic internal javascript class, and that jQuery.type on even a raw HTML element returns "object". In fact, since $slides[2] is a raw HTML element, that's exactly what's happening
Makes perfect sense. I hadn't considered either of your points. In my mind, as $slides was a jQuery object it would remain a jQuery object despite using [ ] but now I understand. Appreciate your time and effort

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.