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]');
Sartheris Stormhammer
  • 2,425
  • 8
  • 34
  • 75

4 Answers4

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?
Community
  • 1
  • 1
Pranav C Balan
  • 110,383
  • 23
  • 155
  • 178
1

You can have .data() function for that

$("#controlid").data("phone-code");
Hemal
  • 3,572
  • 1
  • 21
  • 48
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/

Marco
  • 2,549
  • 20
  • 24
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]');
Aniruddha Das
  • 17,872
  • 16
  • 92
  • 122