简体   繁体   中英

JQuery - get value of data attribute of element in selector, not in attr

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

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?

您可以为此使用.data()函数

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM