Natalie Nicholas
Natalie Nicholas

Reputation: 237

Checking if the class exists on Page using Jquery

I'm trying to check if a class exists using jquery. But something is not going well! for example here's an HTML

<div id="door">
  <!-- change this class to something else to test -->
  <div class="test alfa">
    <h1>Class "Test" Does Exist</h1>
  </div>
</div>

How can I check that the class test exists

I'm trying the following if statement by not working for some reason. it may be something wrong with my code that I can't spot for some reason!

if ($('test')[0]) {
    $('h1').show();
} else {
  $('h1').text('Class "Test" Does NOT Exist');
}

I would appreciate it if you can test this for me or let me know what's going wrong with the above statement!?

Upvotes: 4

Views: 11451

Answers (3)

Manikant Gautam
Manikant Gautam

Reputation: 3591

You forgot putting . on selector

if ($('.test')[0]) {
    $('h1').show();
} else {
  $('h1').text('Class "Test" Does NOT Exist');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="door">
  <!-- change this class to something else to test -->
  <div class="test alfa">
    <h1>Class "Test" Does Exist</h1>
  </div>
</div>

Upvotes: 0

DirWolf
DirWolf

Reputation: 891

You need to add a dot to the test class

if ($('.test')[0]) {
    $('h1').show();
} else {
  $('h1').text('Class "Test" Does NOT Exist');
}

Upvotes: 4

glemmal
glemmal

Reputation: 34

You forgot a "." :

if ($('.test')[0]) {
    $('h1').show();
} else {
  $('h1').text('Class "Test" Does NOT Exist');
}

Upvotes: 0

Related Questions