Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery select element if *any* attribute matches

I want a selector like $(".author") that will select an element if "author" is the value of any attribute, not just class.

E.g. selector.text() should give "Emily Ekins" for each of the following pages:

<a href="http://reason.com/people/emily-ekins" rel="author">Emily Ekins</a>

or

<bloop href="http://reason.com/people/emily-ekins" id="author">Emily Ekins</a>

or

<blah href="http://reason.com/people/emily-ekins" class="author">Emily Ekins</a>

or

<tag href="http://reason.com/people/emily-ekins" random="author">Emily Ekins</a>

Is there any way to do this?

like image 272
tarayani Avatar asked Dec 03 '11 21:12

tarayani


People also ask

Does jQuery support selection based on attributes values?

jQuery [attribute|=value] Selector The [attribute|=value] selector selects each element with a specified attribute, with a value equal to a specified string (like "en") or starting with that string followed by a hyphen (like "en-us"). Tip: This selector is often used to handle language attributes.

How do you find the element based on a data attribute value?

Answer: Use the CSS Attribute Selector You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.

How get data attribute value in jQuery?

To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).


2 Answers

I would use @Web Developer's answer, but will add that if you're going to need to select them multiple times, then it's more efficient to save the selection as a var:

var $target = $("[id='author'],[class='author'],[name='author']");

$target.text();

Here's some documentation on attribute selectors:

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

http://www.w3.org/TR/css3-selectors/#attribute-selectors

https://github.com/jquery/sizzle/wiki/Sizzle-Home (jQuery uses Sizzle)

like image 94
ryanve Avatar answered Oct 13 '22 01:10

ryanve


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 == 'author'){
            element.style.backgroundColor='red';
        }
    }
}

Example

Whew! That took some time. But this will check every single attribute of any given element, and if any attribute is author, it will change the background color to red.

like image 21
Purag Avatar answered Oct 13 '22 01:10

Purag