Which tags can have an onClick
function, and which cannot? If there are any where I cannot include an onClick
function, why not?
onClick="func()"
Are there any rules that you should adhere to?
Which tags can have an onClick
function, and which cannot? If there are any where I cannot include an onClick
function, why not?
onClick="func()"
Are there any rules that you should adhere to?
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).
'"I have the right to do anything," you say -- but not everything is beneficial' - Apostle Paul, 1 Corinthians 6:12
Compare the comments on this post and the resulting link to the MDN web docs which strongly imply that elements such as <div>
and <span>
should not be used for click-actions because they "do not inherently represent anything" and "It should be used only when no other semantic element is appropriate."
You'll see that while it's possible to attach an onclick
to practically anything, some elements have further support for being clicked (or, rather, preventing clicks) and other elements don't.
So, I would recommend that the question be re-phrased to read, "Which HTML tags have full support for onClick?" or something similar. <input>
would be a good example of a tag with full support, and <span>
, therefore, would not.
I, too, would very much like to find a list of HTML tags that are "first-class click citizens" so I can choose my web elements better.
Any element can have an onclick event via ID or class. Using jQuery, this is very easy:
// Talk to any element with a unique ID of "myElementId".
$('#myElementId').on('click', function(event){
alert('CLICK');
// do something else.
event.preventDefault();
});
// Talk to any element with a class of "myClassElement".
$('.myClassElement').on('click', function(event){
alert('CLICK');
// do something else.
event.preventDefault();
}
// Talk to the <header> element.
$('header').on('click', function(event) {
alert('CLICK');
// do something else.
event.preventDefault();
)};
You can check which elements the event can be used on in this sitepoint reference
The full list of elements which don't support it would be: