40

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.

4 Answers 4

86
var number = 6;
var myDiv = $('div[data-divNumber="' + number + '"]');
Sign up to request clarification or add additional context in comments.

1 Comment

So does putting the div in here $('div[... specify only to look at div elements?
8

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"]');

Comments

2

I think what you need is:

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

Comments

1

With ES6 you can use string interpolation:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.