Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does $('el')[0].className work but not $('el').className?

I noticed that className property doesn't work inside jQuery without the index, why is that?

Also, are there other common JS properties / methods that don't work as expected inside jQuery?

HTML:

<div class="par">test</div>

JQuery:

$(function () {

    var el = $('.par');

    el.className += ' new class'; // doesn't work
    el[0].className += ' new class'; // works
});
like image 978
dzumla011 Avatar asked Dec 18 '25 19:12

dzumla011


1 Answers

var el = $('.par'); returns a jQuery object. className is a property on Element and not on jQuery object.

The jQuery object has an array like definition so el[0] returns the underlying Element which has className property.

As far as I know, jQuery doesn't like developer updating its property directly. It simply exposes variety of utility functions for easy developement.

Quoting on a nice comment from David Thomas below,

jQuery methods can only be used on jQuery objects; native DOM properties/methods can only be used on native DOM nodes

Note: var el = $('.par'); returns a collection of Element and el[0] returns the first element in that list.

You could use .addClass to add a class to the element.

To the first element,

el.eq(0).addClass('new_class');

To all elements,

el.addClass('new_class');

More Reading:

  1. https://developer.mozilla.org/en-US/docs/Web/API/element
  2. https://developer.mozilla.org/en-US/docs/DOM/element.className
like image 69
Selvakumar Arumugam Avatar answered Dec 20 '25 08:12

Selvakumar Arumugam



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!