0

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.

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately, I have no control over the HTML as it's being created by a CMS. But this is exactly what I was looking for - thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.