Reputation: 237
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
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
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
Reputation: 34
You forgot a "." :
if ($('.test')[0]) {
$('h1').show();
} else {
$('h1').text('Class "Test" Does NOT Exist');
}
Upvotes: 0