m-use
m-use

Reputation: 363

jQuery - select multiple elements with the same attribute value

I am trying to find a jQuery selector that gets every element with a specific attribute value - not necessarily the same attribute, just the same attribute value. For example, what jQuery selector would pick up each of the following?

<h1 name="test"><h1>
<a id="test"></a>
<p data-attribute="test"></p>

All I can think to try is $("*").attr( "*", "test" ) but that does not work.

Upvotes: 0

Views: 1004

Answers (1)

Neil
Neil

Reputation: 14313

This is a very odd question. It can be accomplished by looping through the attributes of each dom attribute, but I would recommend instead restructuring your HTML so you can use [data-test=true], a data-test attribute with the value of true.

$("*").filter(function() {
  flag = false;
  $.each(this.attributes, function(i, attrib){
    if (attrib.value == "test") {
      flag = true;
    }
  });
  return flag;
}).css("background","red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 name="test">a<h1>
<a id="test">b</a>
<p data-attribute="test">c</p>
<p>don't highlight</p>

Upvotes: 1

Related Questions