pee2pee
pee2pee

Reputation: 3802

jQuery: Can't find button identified by class and data attribute

I have the following code:

jQuery

console.log($("button[class='confirm_button'][data-id='5141']").length);

HTML

<button type="button" class="btn btn-warning btn-xs confirm_button" data-id="5141">Click to confirm</button>

The console.log is triggered on a click of the button. However, I always get a length of zero. I tried hiding/showing it but it was failing so went to see if it existed and got a value of zero for the length.

Anything obvious?

Upvotes: 0

Views: 1435

Answers (3)

mgarcia
mgarcia

Reputation: 6325

The selector

$("button[class='confirm_button'][data-id='5141']")

is searching for an element with button tag, that has an attribute class that is equal to confirm_button and another attribute data-id with value 5141.

This selector is not selecting the button

<button type="button" class="btn btn-warning btn-xs confirm_button" data-id="5141">Click to confirm</button>

because this button does not have an attribute class with value confirm_button but instead has an attribute class with value btn btn-warning btn-xs confirm_button.

If you want to select a button with a specific class, you could use the selector:

$("button.confirm_button[data-id='5141']")

Upvotes: 0

Naga Sai A
Naga Sai A

Reputation: 10975

To achieve expected result, use Attribute Contains Word Selector '~' instead of Attribute Equals Selector '='

Issue: using class with '=' should match exact class - 'btn btn-warning btn-xs confirm_button'

As per official jQuery documentation ,

Attribute Equals Selector [name=”value”]
Selects elements that have the specified attribute with a value exactly equal to a certain value.

$('button').on('click', function(){
  console.log($("button[class~='confirm_button'][data-id='5141']").length);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-warning btn-xs confirm_button" data-id="5141">Click to confirm</button>

Please find all the attribute type options - https://api.jquery.com/category/selectors/attribute-selectors/

Codepen - https://codepen.io/nagasai/pen/agmzKj?editors=1010

Upvotes: 0

shrys
shrys

Reputation: 5960

Try giving console.log($("button[class$='confirm_button'][data-id='5141']").length); which checks if class ends with given string

Upvotes: 1

Related Questions