Jquery - How to Select by Attribute

Setting the selected attribute on a select list using jQuery

If you don't mind modifying your HTML a little to include the value attribute of the options, you can significantly reduce the code necessary to do this:

<option>B</option>

to

<option value="B">B</option>

This will be helpful when you want to do something like:

<option value="IL">Illinois</option>

With that, the follow jQuery will make the change:

$("select option[value='B']").attr("selected","selected");

If you decide not to include the use of the value attribute, you will be required to cycle through each option, and manually check its value:

$("select option").each(function(){
if ($(this).text() == "B")
$(this).attr("selected","selected");
});

jQuery : select all element with custom attribute

Use the "has attribute" selector:

$('p[MyTag]')

Or to select one where that attribute has a specific value:

$('p[MyTag="Sara"]')

There are other selectors for "attribute value starts with", "attribute value contains", etc.

jQuery - How to select value by attribute name starts with

If you want all data-* attributes, you can iterate through jq data object:

$('.slide').each(function(){
for(data in $(this).data())
console.log(data); // returns confirmID so element as an attribute `data-confirmID`
});

But this data object can contains other keys which aren't attribute, setted for example by some plugins.

EDIT

To get all kinds of attribute to "starts with", you can customize your own jQuery selector:

jQuery.extend(jQuery.expr[':'], {    attrStartsWith: function (el, _, b) {        for (var i = 0, atts = el.attributes, n = atts.length; i < n; i++) {            if(atts[i].nodeName.toLowerCase().indexOf(b[3].toLowerCase()) === 0) {                return true;             }        }                return false;    }});
//e.g:$('.slide:attrStartsWith("data-")').css('color', 'red');$('.slide:attrStartsWith("conf")').css('color', 'blue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><div class="slide" data-confirmID="46" data-testID="666">1</div><div class="slide" confirmID="54" >2</div>

How to select a specific tr based on attribute value

You can select elements by what an attribute's value is equal to like this:

var element = $('th[aria-controls="dog"]')

More info on attribute equals selector here: https://api.jquery.com/attribute-equals-selector/

As a side note the th is not even necessary or the attribute's value to test against. You can simply select all elements with that attribute regardless of its value too like this:

var element = $('[aria-controls]')

There are many ways of using this selector. You can even find elements with that attribute that start, end or contain the value.

Starts with: var element = $('[aria-controls|="dog"]') ex: dogggg

Ends with: var element = $('[aria-controls$="dog"]') ex: adog

Contains: var element = $('[aria-controls*="dog"]') ex: bdogb

Not equal: var element = $('[aria-controls!="dog"]') ex: cat

More info on attribute selectors in general here: https://api.jquery.com/category/selectors/attribute-selectors/

jQuery select by attribute using AND and OR operators

AND operation

a=$('[myc="blue"][myid="1"][myid="3"]');

OR operation, use commas

a=$('[myc="blue"],[myid="1"],[myid="3"]');

As @Vega commented:

a=$('[myc="blue"][myid="1"],[myc="blue"][myid="3"]');

jQuery how to find an element based on a data-attribute value?

You have to inject the value of current into an Attribute Equals selector:

$("ul").find(`[data-slide='${current}']`)

For older JavaScript environments (ES5 and earlier):

$("ul").find("[data-slide='" + current + "']"); 

Select elements by attribute

Do you mean can you select them? If so, then yes:

$(":checkbox[myattr]")

How to select element has attribute and attribute not equal to specific value using jquery?

JQuery Has Attribute Selector [name] select element only has attribute without consider to it value. You need to adding [attr] at the first of your selector.

$("ul").find("[class][class!='A']").css("color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ul>  <li class="A">A</li>  <li class="A">A</li>  <li class="B">B</li>  <li>C</li></ul>

jQuery select by class VS select by attribute

this is a great post for exactly what you are looking for.

JQUERY SELECTOR PERFORMANCE TESTING

I've also found a great article that may help you on this topic:

  • some jquery selectors performance tests

let me know if this answer really helped you, thanks.

update: I've managed to make a sample to match your posted case, here are the results for a total set of 203 divs:

1- by using tag name having certine class name $("div.normal_box") ==> 884 ms

2- by using attribute value $("div[normal_box=1]") ==> 4553 ms

Update 2:
I tried even further more than your question, and made it to test a few selectors, here is the new link for this updated test: http://jsfiddle.net/8Knxk/4/

3- by using tag name $("div") ==> 666 ms

4- by using just the class name $(".normal_box") ==> 762 ms

I think it's now more clear for you :)

Selecting element by data attribute with jQuery

$('*[data-customerID="22"]');

You should be able to omit the *, but if I recall correctly, depending on which jQuery version you’re using, this might give faulty results.

Note that for compatibility with the Selectors API (document.querySelector{,all}), the quotes around the attribute value (22) may not be omitted in this case.

Also, if you work with data attributes a lot in your jQuery scripts, you might want to consider using the HTML5 custom data attributes plugin. This allows you to write even more readable code by using .dataAttr('foo'), and results in a smaller file size after minification (compared to using .attr('data-foo')).



Related Topics



Leave a reply



Submit