I have the following element:
<h1 msgId = "someId"> Some text </h1>
and in a code.js the following function:
document.addEventListener('click', function(e) {
target = e.target;
}, false);
I need to obtain the string "someId" in msgId property. Something like target.msgId
document.addEventListener('click', function(e) {
id = e.target.msgId;
}, false);
Thank you in advance
msgId
is an attribute on that element, so you'd use getAttribute
:
console.log(e.target.getAttribute("msgId"));
Live Example:
document.addEventListener('click', function(e) { console.log(e.target.getAttribute("msgId")); }, false);
<h1 msgId = "someId"> Some text </h1>
However , if you're going to use your own attributes, use a data-
prefix; see the spec for details.
You can use Element.getAttribute to get the value of msgId
attribute.
document.addEventListener('click', function(e) { target = e.target.getAttribute("msgId"); console.log(target); }, false);
<h1 msgId = "someId"> Some text </h1>
I would still suggest you to use data-msgId
as msgId
will not be a valid HTML5 attribute.
This should work e.target.getAttribute("msgId");
But I would suggest use data-attribute
since it will be valid HTML5 attribute
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.