Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Find the element with a particular custom attribute

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

E.g. 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.

like image 881
Chro Avatar asked Dec 25 '11 05:12

Chro


2 Answers

var number = 6; var myDiv = $('div[data-divNumber="' + number + '"]'); 
like image 172
Ali Foroughi Avatar answered Sep 19 '22 23:09

Ali Foroughi


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"]'); 
like image 42
jfriend00 Avatar answered Sep 19 '22 23:09

jfriend00