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,534
  • 8
  • 37
  • 81

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
  • 113,687
  • 23
  • 165
  • 188
1

You can have .data() function for that

$("#controlid").data("phone-code");
Hemal
  • 3,682
  • 1
  • 23
  • 54
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,757
  • 1
  • 19
  • 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
  • 20,520
  • 23
  • 96
  • 132