Felipe Costa Gualberto
Felipe Costa Gualberto

Reputation: 1107

jQuery selector for other attributes than id doesn't work in the same way

In a HTML page, if I type in my console $("#title")[0], I get:

<div id="title" class="ms-font-xxl ms-fontColor-neutralSecondary ms-fontWeight-semilight">Change Case</div>

Ok. If I type $("#title")[0].id, I get "title".

The problem is when I type $("#title")[0].class, I get undefined.

Shouldn't I get ms-font-xxl ms-fontColor-neutralSecondary ms-fontWeight-semilight? What did I do wrong?

Upvotes: 1

Views: 77

Answers (2)

Dalin Huang
Dalin Huang

Reputation: 11342

Two way of getting it:

Before jQuery 1.6, use .attr() After jQuery 1.6+, use .prop()

  1. jQuery method .prop(): $('#title').prop('class')

  2. JS method .className: $('#title')[0].className

Since you are using jQuery, just go 1st option =D

.prop

REF: http://api.jquery.com/prop/

Element.className

REF: https://developer.mozilla.org/en-US/docs/Web/API/Element/className

console.log($('#title').prop('class'));
console.log($('#title')[0].className);

//get array of class name
console.log($('#title')[0].className.split(/\s+/));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="title" class="ms-font-xxl ms-fontColor-neutralSecondary ms-fontWeight-semilight">Change Case</div>

Upvotes: 5

James Maa
James Maa

Reputation: 1794

Try

$('#title').attr('class')

Not all the attributes could be grabbed instantly

Upvotes: 1

Related Questions