简体   繁体   中英

How can I select an element which has only a specific class?

Here is my selector:

doc.on("click", ".add_your_qora", function(e){

My code will select this:

<div class="add_your_qora"> whatever </div>

My code will select this too:

<div class="add_your_qora another_class_name"> whatever </div>

All I'm trying to do is avoiding it. The second element shouldn't be selected, because it doesn't have only add_your_qora class. How should I write my selector?

Check if the current element Element.classList length is greater than 1:

 $(doc).on("click", ".add_your_qora", function(e) { if (this.classList.length > 1) return; console.log($(this).text()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="doc"> <button class="add_your_qora">only add_your_qora</button> <button class="add_your_qora another_class">has another class as well</button> </div> 

If the element you want is the first one with this class you can use document.querySelector('.add_your_qora') which will return only the first element found that matches the selector.

If you want to select all the elements that has add_your_qora class except those which also have another_class you can use $('.add_your_qora:not(.another_class)') .

If you want to select all the elements that have only add_your_qora class use this selector [class=another_class]

alternative way,

 $(function(){ $(document).on('click', '.add_your_qora', function(e){ if ($(this).attr('class').match(/^add_your_qora$/) == null) return; alert($(this).text()); }); }); 
 <script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div class="add_your_qora"> add_your_qora </div> <div class="add_your_qora another_class_name"> add_your_qora another_class_name </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM