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.

Avatar photo
👋 Hey, I'm Osman Armut
Hi, I'm Osman Armut. I'm a self taught frontend developer that has a great passion for Javascript and React ecosystem. I use articles in my personal learning journey and I like to share my knowledge to help people.

💬 Leave a comment

Your email address will not be published. Required fields are marked *

We will never share your email with anyone else.