You’re likely getting this error because you’re trying to get a name attribute on elements that don’t have a name attribute. For example; input, textarea, and form elements are naturally able to get a name attribute. But elements like div, span doesn’t.
So, you’re probably trying to get name attribute of a div or span element like this:
<div
name="helloDiv"
onclick="clickHandler()">
Hello
</div>
function clickHandler(event){
const name = event.target.name;
console.log(name);
}
//Error: event.target.name is undefined
As we said, div elements can not have name attribute naturally.
If we give a name attribute to a div , it’ll be a custom attribute and we can get a custom attribute using something like this:
<div
name="helloDiv"
onclick="clickHandler()">
Hello
</div>
function clickHandler(event){
const name = event.target.getAttribbute("name");
console.log(name);
}
//helloDiv
Using the above technique, you can give name attributes (or any other custom attribute you want) to any element.
And this is it for this article. I hope you enjoyed it.
💬 Leave a comment