0

I am always looking for a shorter and faster way of making jQuery selections, and I wondered if there is a shorter way to select the value of the data attribute of a given element. Now I have this

const phoneCode = $('#loginCountryCodeInput').attr('data-phone-code');

to get the value of this data attribute

<input id="loginCountryCodeInput" data-phone-code="+1">

Is there a shorter selector, something like this?

const phoneCode = $('#loginCountryCodeInput[data-phone-code]');
1
  • No, it doesn't work that way! Commented Feb 10, 2017 at 12:03

4 Answers 4

3

Use data() method to get custom data-* attribute value.

$('#loginCountryCodeInput').data('phone-code');


FYI : There is no way to get the value by a selector, which generates a jQuery object.
There are some difference between the methods : jQuery Data vs Attr?

Sign up to request clarification or add additional context in comments.

2 Comments

Nice but the question is to achieve it by selectors :)
@Marco : there is no way to get it's value, simply using selector :)
1

You can have .data() function for that

$("#controlid").data("phone-code");

Comments

0

Yes there is. It's almost like the one you wrote, but you need to use $("#id-of-element[property='value']"). E.g.: $("#loginCountryCodeInput[data-phone-code='+1']")

Source documentation: https://api.jquery.com/attribute-equals-selector/

Comments

0

try this. there any other answer available. take which one best suite for you.

document.querySelectorAll('[data-phone-code="+1"]');
$('a[data-phone-code=+1]');

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.