admin管理员组文章数量:1291041
Goal: get the data-element
from the button that is been clicked.
My current code:
Array.from(document.getElementsByClassName('my_buttons_class')).forEach((button) => {
button.addEventListener('click', (e)=>{
e.preventDefault();
/*
Here i want to get the 'data-element' from the clicked button
something like
e.target.attr('data-element');
*/
})
});
The button element is something like this:
<button class="my_buttons_class" data-element="some json">My button text</button>
Current problem: the listener works fine, but the e.target
is just the HTML text of that element, so i can't use .attr()
on it
Also already tried e.target['data-element']
but it return undefined
Goal: get the data-element
from the button that is been clicked.
My current code:
Array.from(document.getElementsByClassName('my_buttons_class')).forEach((button) => {
button.addEventListener('click', (e)=>{
e.preventDefault();
/*
Here i want to get the 'data-element' from the clicked button
something like
e.target.attr('data-element');
*/
})
});
The button element is something like this:
<button class="my_buttons_class" data-element="some json">My button text</button>
Current problem: the listener works fine, but the e.target
is just the HTML text of that element, so i can't use .attr()
on it
Also already tried e.target['data-element']
but it return undefined
3 Answers
Reset to default 5.attr()
is a jQuery method, In vanilla JavaScript you have to use getAttribute()
to access the attribute:
e.target.getAttribute('data-element');
Array.from(document.getElementsByClassName('my_buttons_class')).forEach((button) => {
button.addEventListener('click', (e)=>{
e.preventDefault();
console.log(e.target.getAttribute('data-element'));
});
});
<button class="my_buttons_class" data-element="some json">My button text</button>
The button
variable refers to the button being iterated over, so to access the data-element
attribute of that element, use:
button.dataset.element
or, with getAttribute
:
button.getAttribute('data-element')
Elements do not automatically get their attributes assigned as properties of their Javascript references - that only works for a certain few attribute types, like id
, class
, and name
, which is why e.target['data-element']
didn't work.
Try using getAttribute
:
Array.from(document.getElementsByClassName('my_buttons_class')).forEach((button) => {
button.addEventListener('click', (e)=>{
e.preventDefault();
console.log(e.target.getAttribute('data-element'));
})
});
<button class="my_buttons_class" data-element="some json">My button text</button>
本文标签: htmlGet an attribute from the clicked element with JavascriptStack Overflow
版权声明:本文标题:html - Get an attribute from the clicked element with Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741523839a2383350.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论