I'm trying to get the data-form-id
value from the following HTML, but a console.log(formID);
returns undefined
?
Edit:
My bad, the class is actually .hs-form
, typo on my end.
(function($) { $(document).ready(function() { var formID = $(".hs-form").data("form-id"); console.log(formID); }); })(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form class="hs-form" data-form-id="1abe6767-4f6b-40c1-acb4-1b85bf33c932">
From jQuery .data() documentation:
The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.
So you need to use .attr()
if you want to get the value of data-* attributes.
Using the data() method to update data does not affect attributes in the DOM. To set a data-* attribute value, use attr.
Also, you don't have .hs-form
in your html.
If you prefer to use .data()
you need to set the value first using .data( key, value )
(function($) { $(document).ready(function() { var formID = $("form").attr("data-form-id"); console.log(formID); }); })(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form class="form" data-form-id="1abe6767-4f6b-40c1-acb4-1b85bf33c932">
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.