SoFunction
Updated on 2025-03-01

JS JQuery to obtain data-* attribute value method analysis

Here are four methods to obtain the value of the data-* attribute

<li data- data-vice->get id</li>

What needs to be obtained are the values ​​of data-id and dtat-vice-id

1: getAttribute() method

const getId = ('getId');
// //getAttribute() value attribute(("data-id"));//122
(("data-vice-id"));//11
// //setAttribute() Assign attribute("data-id","48");
(("data-id"));//48

Two: dataset() method

//data-prefix attribute can be used to get values ​​in JS through dataset, which is more convenient();//112
//Data-vice-id connection value is used to get the value using camel nomenclature();//11

//Assignment = "113";//113
--;//10

//Add data attributes.id2 = "100";//100

//Delete, set to null, or delete.id2 = null;//null
delete .id2;//undefind

Three: jquery data() method

var id = $("#getId").data("id"); //122
var viceId = $("#getId").data("vice-id"); //11
//Assignment$("#getId").data("id","100");//100

jquery data is a caching mechanism

The usage is as follows:

data()method

//HTML code <div data-app data-myname="lsxj" data-app- data-my-name="secondname"></div>
//Get attributevar appid = $("#myDiv").data("appid"); //123
var app-id = $("#myDiv").data("app-id"); //456

//Attribute assignment $("#myDiv").data("appid","666");
//The final HTML code <div data-app data-myname="lsxj" data-app- data-my-name="secondname"></div>
It should be noted that,data()Modifying the value will not affectDOMOn the elementdata-*Changes in attributes。data()The essence of “cache” Attached to the object,and a special attribute name is used。

So in the above code,Although it is correctdivProgresseddata()Assignment operation,butHTMLIn codedivofdata-appidof值仍然为123,becausedata()只是修改了缓存of那个值,Proceed now$('#myDiv').data("appid")of操作,输出of结果为666.

Four: jquery attr() method

var id = $("#getId").attr("data-id"); //122
var viceId = $("#getId").attr("data-vice-id"); //11
//Assignment$("#getId").attr("data-id","100");//100

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.