Martin AJ
Martin AJ

Reputation: 6697

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?

Upvotes: 1

Views: 951

Answers (3)

Anfath Hifans
Anfath Hifans

Reputation: 1598

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>

Upvotes: 0

Elie G.
Elie G.

Reputation: 1723

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]

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191966

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>

Upvotes: 2

Related Questions