I have a header element which needs to fire off some JavaScript when clicked. I know I should only use <a> tags when the page is actually changing, and that <button>s are preferred for JS functions, but for some reason it just feels wrong to do

<h2><button onclick="myFunction();">My Title</button></h2> 

I can't put my finger on why that doesn't feel semantically correct. Is it just me?

4

3 Answers

According to W3C Validator, there's no problem in doing that.

You can try validating this code:

<!DOCTYPE html> <html> <head> <title>I AM YOUR DOCUMENT TITLE REPLACE ME</title> </head> <body> <h2><button onclick="myFunction();">My Title</button></h2> </body> </html> 

However, I suggest avoiding inline styles.

7

What is the actual text for your button? Would it be appropriate as a heading on it's own?

the text for the button is the title of the content that's being revealed onclick

Then I think you're in good shape. I will however make a small suggestion that might make you feel better:

<h2><a href="#content">My Heading</a></h2> <element> [your content] </element> 

Then attach an onclick handler in an external javascript file. If you remove it later the link will still be valid.

HTML5 standard quote that says you can

4.3.6 The h1, h2, h3, h4, h5, and h6 elements says that those elements can only have phrasing content ("inliny things" like bold or italics or links):

Content model: Phrasing content.

And says that button is phrasing content:

So you can nest them.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy