Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get elements by a specific value of a custom attribute in jQuery?

I have a custom attribute called data-role and I'd like to find all elements where data-role="content" in jQuery.

enter image description here

I'm currently doing this with some old JavaScript code:

var elements = element.getElementsByTagName(tagName);
for(var i=0; i<elements.length; i++) {
  if(elements[i].getAttribute("data-role") == "content") {
    // does something evil
  }
}

Disclaimer: Code was not checked, just wrote it down quickly.

I've got a feeling that there's an elegant 1-line solution in jQuery, but I'm a novice. And I can't sleep before I know, so perhaps you stackoverflowers can help a bro out. ;-)

like image 945
beta Avatar asked Dec 25 '22 23:12

beta


2 Answers

$("tagName[attribute='value']")

Or, in your case:

$("div[data-role='content']")

Will return the right elements.

From there, if you wanted to iterate over the set of elements that match this selector and do something evil, you could:

$("[data-role='content']").each(function(index){

     Do something evil
     $(this) is the current element in the iteration
});

Please note that the tagName is optional. JQuery selectors can be concatenated at will, so you can query simulataneously for tagname (simple string), id (prefaced by #), class (prefaced by .) or attribute (in square brackets as above), or for any limited combination of them eg:

 $("tagName#someId.someClass.someOtherClass[attribute='value']")
 $("[attribute='value']")
 $('tagName')
 $('#someId')

Are all valid queries, however keep in mind that jquery will only return elements that match ALL conditions in the query.

like image 135
Abraham P Avatar answered Apr 19 '23 22:04

Abraham P


Check out jQuery's list of attribute selectors. You're looking for something like

$('div[data-role="content"]')
like image 21
UweB Avatar answered Apr 19 '23 21:04

UweB