How can I get the '123' value from the following code? I thought the snippet should work but I instead get email :....
<div id="home">
<div class="name" my-data="123">Email: [email protected]</div>
</div>
var element = document.querySelector('.element');
var dataAttribute = element.getAttribute('my-data');
console.log(dataAttribute);
CodePudding user response:
You try to use querySelector
with .element
, that class doens't exist instead you need to use .name
var element = document.querySelector('.name');
var dataAttribute = element.getAttribute('my-data');
console.log(dataAttribute);
<div id="home">
<div class="name" my-data="123">Email: [email protected]</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Just for your knowledge you could use data-attribute
like this:
var element = document.querySelector('.name');
var dataAttribute = element.getAttribute('data-email');
console.log(dataAttribute);
<div id="home">
<div class="name" data-email="123">Email: [email protected]</div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Reference:
CodePudding user response:
When using a custom attribute, make sure to write "data-", and then the rest of the attribute name. Doing that, you can easily access the data from javascript.
<div class="name" data-something="123">Email: test@gmail.com</div>
And for the js:
let element = document.querySelector('.name')
let dataAttribute = element.dataset.something