4

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!?

4
  • 1
    $('test') is missing . for class Commented Dec 9, 2017 at 12:13
  • And perhaps you know can use $('.test').length instead of $('test')[0] Commented Dec 9, 2017 at 12:17
  • You can use hasClass from Jquery if you know where it is. Have a look at the following link it can help you api.jquery.com/hasclass I find that useful. Commented Dec 9, 2017 at 12:22
  • Depending your real use case, I guess you haven't to use any js/jQuery but just CSS would be enough Commented Dec 9, 2017 at 12:34

3 Answers 3

4

You need to add a dot to the test class

if ($('.test')[0]) {
    $('h1').show();
} else {
  $('h1').text('Class "Test" Does NOT Exist');
}
Sign up to request clarification or add additional context in comments.

Comments

0

You forgot a "." :

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

Comments

0

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.