Manish
Manish

Reputation: 6286

Getting the class(s) of a div using jquery

Well I already saw this question here. But m a little bit of confused. There were several solutions provided:-

  1. var div1Class = $('#div1').attr('className');

    This one was the accepted solution with 2 up votes.

  2. var divClass = $("#div1").attr("class")

    This got an up vote too.

Which is the correct one? And if both are correct, what is the difference between the two?

Upvotes: 1

Views: 175

Answers (2)

manji
manji

Reputation: 47968

it's permissible to use 'class', jQuery will fix it, but jQuery recommands to use 'className' Attributes/attr

to avoid collision with classes definition, DOM renamed 'class' attribute to 'className'. same thing for the 'for' attribute that was renamed 'htmlFor'. (see here :1.6.2. Naming Exceptions)

Upvotes: 5

Mark Bell
Mark Bell

Reputation: 29785

There is no HTML attribute className - the correct code is:

var divClass = $("#div1").attr("class");

className is a Javascript DOM property, so if you weren't using jQuery you could do:

var divClass = document.getElementById('div1').className;

Upvotes: 3

Related Questions