Which HTML tags can be used with onClick?
11,698
All HTML elements can have an onclick
attribute.
See the HTML 5 specification for confirmation.
(Of course, some elements are not rendered by default so you would have to alter their display
properties with CSS before they can be clicked on to trigger the event handler).
Related videos on Youtube
Author by
Mario Boss
const describeMe = prompt('How you can describe me?'); const regex = /not|BAD|AS{1,2}|for|a|dev+/igm; alert('Your description is ' + regex.test(describeMe));
Updated on June 05, 2022Comments
-
Mario Boss almost 2 years
Which HTML tags can have an
onclick
event and which cannot? If there are tags where I cannot include anonclick
event I want to know why not?onclick="func()"
Are there any rules that you should adhere to?
-
Laurent S. about 10 yearsas a side remark, you should avoid inline javascript...
-
-
pes502 about 10 yearsI think, that he talking about HTML tags, not about element classes or id's
-
Admin about 10 yearsto include an onClick in a html or title tag is nonsensical, but i can do this?
-
TylerH about 10 yearsYes you can do this, but it is not recommended as it is obtrusive.
-
Quentin about 10 yearsIt isn't nonsensical. The html element is rendered, so you could bind an event handler to it to trigger if any part of the document is clicked (quite useful if you want to generate heat maps of your page, although I'd tend to bind directly on the
window
object myself). It is rather odd to make a title clickable, buthead, title { display: block; }
in a stylesheet will make it possible. -
Damon about 10 yearsI would strongly advise not mixing your js within your html by adding an "onClick" attribute to your html whenever possible. Linking to an external js file - that hooks into your markup is the ideal way to roll. The above is how you would do that.
-
Damon about 10 yearsEDIT: I updated the js to show how you can talk directly to the element. Be sure your element in question has loaded & is available before talking to it. Otherwise, nothing will happen. Use these calls within a/an onready statement (or at the bottom of your html).
-
Daniel Bragg about 5 years@TylerH, so what elements are there for which this is recommended and non-obtrusive?
-
TylerH about 5 years@Dan Most others below
<body>
, frankly. -
Daniel Bragg about 5 years@TylerH "below <body>"? Do you mean "most elements that can appear within the <body> tag, except for <div> and <span>", or elements that are listed somewhere in a list where "body" is in the middle of the list?
-
TylerH about 5 years@Dan I mean the former.