JQuery selector using value but unknown attribute

How can I use jQuery to search for elements that have a specific attribute value, regardless of the attribute tag?

how

$("[*='myvalue']") 

should find

 <a href="target.html" target="myvalue">... <tr change="myvalue">... 

The first, because of the attribute "target", the second for the attribute "change".

Is there a better solution than just looping through all the attributes?

+7
javascript jquery
source share
3 answers

You can use a custom pseudo selector to filter by attribute.

The following is a jQuery method.

 $.expr[":"].attrFilter = function(elem, index, val){ var len = $(elem.attributes).filter(function () { return this.value === val[3]; }).length; if (len > 0) { return elem; } }; $('body *:attrFilter("value")').hide(); 

Demo Screenshot

$.expr[":"].attrFilter , is an extension mechanism for custom selectors. You can also pass a parameter.


Syntax :

 $.expr[':'].selector = function(elem, index, match) { } 
  • elem - current DOM element
  • index is the elem index
  • match is an array containing all the information about the user selector, where the passed parameter lies in the third index. ( Link 1 , Link 2 )

    • match[0] - contains a full pseudo-class selector call. In this example: attrFilter("value")
    • match[1] - contains only the name of the selector. In this example attrFilter
    • match[2] - indicates which type of quotation marks, if any, is used in the parameter expression. that is, single (') or double ("). For example, it will be empty.
    • match[3] - gives us parameters, ie what is in brackets. In this example, `value
+2
source share

Yes, the same approach will also be used here. Link

  var elements = document.getElementsByTagName("*"); for (var i = 0; i < elements.length; i++) { var element = elements[i]; var attr = element.attributes; for (var j = 0; j < attr.length; j++) { if (attr[j].nodeValue == 'myvalue') { element.style.backgroundColor = 'red'; } } } 
0
source share

Here is an extension of a function that you can use to find the elements you need.

 jQuery(function($) { $.fn.filter_by_attr_value = function(value) { return this.filter(function() { // [].some() would be better here return $.grep(this.attributes, function(attr) { return attr.nodeValue == value; }).length; }); }; $('*').filter_by_attr_value('myvalue').css('background', 'lightgreen'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="target.html" target="myvalue">FOO</a> <table> <tr change="myvalue"> <td>BAR</td> </tr> </table> <div>not me</div> 
0
source share

All Articles