ahmet
ahmet

Reputation: 5005

If statement to find a class in javascript

<div onclick="showCustomerResultsTable();"
 class="csq-tab ui-state-default ui-corner-top"
 id="customers-tab">Customers</div>  

<div onclick="showParcelJourneySummary();"
 class="csq-tab ui-state-default ui-corner-top ui-state-active"
 id="order-journey-summary-tab">Status History</div>

Using javascript how can I check which one of these have ui-state-active, because I need an if statement to check whether the ui-state-active is activated on status history and do something.

Upvotes: 2

Views: 10946

Answers (3)

m1.
m1.

Reputation: 1325

You could use jQuery's hasClass().

Otherwise you need to check the className property of the element w/ plain ol' JavaScript.

Upvotes: 2

Johan Lindskogen
Johan Lindskogen

Reputation: 1306

This can easily be checked with the new HTML5 classList API:

document.getElementById('customers-tab').classList.contains('ui-state-active');
// Will return true if element has class

Otherwise, you'll have to use the old way:

document.getElementById('customers-tab').className.indexOf('ui-state-active') != -1;
// Will return true if element has class

I would recommend using the hasClass() property in jQuery though!

Upvotes: 3

Ian Bishop
Ian Bishop

Reputation: 5205

var statusHistory = document.getElementById('order-journey-summary-tab');

if(statusHistory.classList.contains('ui-state-active')) {
    // do stuff
}

or if you have jQuery

if($('#order-journey-summary-tab').hasClass('ui-state-active')) {
    // do stuff
}

Upvotes: 3

Related Questions