javascript - can we pass a variable to data attribute of html - Stack Overflow

So far I know that we can store data in html element by using:<divdata-test="hello">

So far I know that we can store data in html element by using:

<div  data-test="hello">
$.("div").data("test")

However , I just can store raw text for data attribute

what I need is:

var t= hello
<div data-test=t>

but when I tried this , it shows the letter t instead of hello.

So far I know that we can store data in html element by using:

<div  data-test="hello">
$.("div").data("test")

However , I just can store raw text for data attribute

what I need is:

var t= hello
<div data-test=t>

but when I tried this , it shows the letter t instead of hello.

Share Improve this question edited Sep 5, 2017 at 7:27 Suren Srapyan 68.7k14 gold badges125 silver badges117 bronze badges asked Sep 5, 2017 at 7:16 Jake LamJake Lam 3,4723 gold badges28 silver badges52 bronze badges 1
  • You should read up on the difference between HTML and the DOM, particularly the difference between HTML attributes and DOM node properties. – Lennholm Commented Sep 5, 2017 at 7:21
Add a ment  | 

5 Answers 5

Reset to default 5

Actually you are changing not the attribute but an property of the DOM object. For data JavaScript has it's own mechanism to hold data for the elements. For more take a look on Documentation.

You can change the data using jQuery (as you have already used it). Use data function and pass your variable as the second argument to the function like $("#d").data("test", t);

console.log($("#d").data("test"));

const t = 'hello';
$("#d").data("test", t); // <- second parameter

console.log($("#d").data("test"));
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d" data-test="test">

You can use the attr() function of JQuery instead of data()

var t= 'hello';
$("div").attr("data-test",t);
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div  data-test=t>asd

Without jQuery

jQuery is definitely unnecessary in this case. You can achieve the same thing with this code

HTML

<div data-test="hello">

JS

const textToChange = 'other text';
const divWithDataAttribute = document.querySelector('[data-test]');
diveWithDataAttribute.dataSet.test = textToChange;

Conclusion

This will apply the new result to the data attribute and we didn't need jQuery.

A thing to note is the part dataSet.test this part es from the data-test attribute. We drop the data- part and camel case the rest of the words.

For example data-test-new-test="whatever" bees testNewTest when accessing the dataSet.

yes you can try this:

 $("div").attr("data-test", "test");
var t="hello";
$("div").attr("data-test",t);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743890305a4524768.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信