-1

I want to set a listener to handle button clicks which I know could be done with:

$("#id").click(function() {...});

but i was wondering if there is a way to make it listen to an attribute rather than an ID. because i would like to add custom attributes for example

<span class="btn btn-primary" button-type="css-change"></span>

and i would like to do something like

$(document).attr("button-type").equals("css-change").click(function () { ... } );

is this at all possible?

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • Please bear in mind that while, in HTML5, custom attributes are valid, they're *only* valid using the `data-` prefix (so: `data-btn-primary`, `data-button-type`, etc). – David Thomas Oct 09 '14 at 15:54
  • Please note: You can only bind event listeners to *DOM nodes*, not IDs or attributes. The selector (that's what you are referring to by ID or attribute, e.g. `#id`) is just means to *find* the right DOM nodes. – Felix Kling Oct 09 '14 at 16:05

4 Answers4

3

Use attribute-equals selector [attribute='value']

$("[button-type='css-change']").click(function() {
  alert("clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<span class="btn btn-primary" button-type="css-change">hi</span>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

You can use the attribute-equals selector:

$("[button-type='css-change']")

Altho you should stick with data-* for custom attributes to pass validation.

$("[data-type='css-change']")
David Thomas
  • 249,100
  • 51
  • 377
  • 410
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

You can do this with a attribute selector.

http://api.jquery.com/category/selectors/

In your case the:

http://api.jquery.com/attribute-equals-selector/

David Thomas
  • 249,100
  • 51
  • 377
  • 410
svema
  • 35
  • 6
0

yes you can loop though all the elemnts in the .btn class ..

<span id="1" class="btn btn-primary" button-type="css-change"></span>
<span id="2" class="btn btn-primary" button-type="test"></span>

 <script>

 $(".btn").each(function()
 {
    if($(this).attr("button-type") == "css-change")
    {
        console.log("The winner is  "+$(this).attr("id"));
    }
 });

 </script>

or there is also an easier way ..

$("[button-type='css-change']").each(function(index)
{
    $(this).html("hi");
}
Wracker
  • 589
  • 10
  • 32