简体   繁体   中英

jQuery: Find the element with a particular custom attribute

I just want to find the element with a particular value for a custom attribute.

Eg I want to find a the div which has the attribute data-divNumber="6" .

var number = 6;
var myDiv = $('[data-divNumber = number]');

I tried using http://api.jquery.com/attribute-equals-selector/ but what I've done doesn't work.

There is precisely one element with that particular value for the attribute.

var number = 6;
var myDiv = $('div[data-divNumber="' + number + '"]');

You need to do some string addition to get the number into your selector and the value needs to be quoted.

var number = 6;
var myDiv = $('[data-divNumber="' + number + '"]');

What you're trying to produce after the string addition is this result:

$('[data-divNumber="6"]');

I think what you need is:

var number = 6;
var myDiv = $('[data-divNumber="'+number+'"]');

With ES6 you can use string interpolation:

let number = 6;
let myDiv = $(`div[data-divNumber="${number}"]`);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM