最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Checking if the class exists on Page using Jquery - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question edited Dec 9, 2017 at 12:11 DirWolf 8916 silver badges24 bronze badges asked Dec 9, 2017 at 12:09 Natalie NicholasNatalie Nicholas 2371 gold badge2 silver badges9 bronze badges 4
  • 1 $('test') is missing . for class – guradio Commented Dec 9, 2017 at 12:13
  • And perhaps you know can use $('.test').length instead of $('test')[0] – Pedram 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./hasclass I find that useful. – DirWolf 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 – A. Wolff Commented Dec 9, 2017 at 12:34
Add a ment  | 

3 Answers 3

Reset to default 4

You need to add a dot to the test class

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

You forgot a "." :

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

You forgot putting . on selector

if ($('.test')[0]) {
    $('h1').show();
} else {
  $('h1').text('Class "Test" Does NOT Exist');
}
<script src="https://ajax.googleapis./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>

发布评论

评论列表(0)

  1. 暂无评论