Max Travis
Max Travis

Reputation: 1328

Should <button> contain nested DOM element or not?

I did not realize is it bad or not, according to the W3C rules about HTML semantic writing - how we should write the button element with descended elements?

In way, like this one:

<button>
 <div>
   <span>'hi'</span>
 </div>
</button>

or only this:

<button>'hi'</button>

Upvotes: 6

Views: 1038

Answers (4)

brk
brk

Reputation: 50346

I tested your code in W3C Validator & the error shown is

Element div not allowed as child of element button in this context. (Suppressing further errors from this subtree.)

W3C Validator result

Upvotes: 5

unor
unor

Reputation: 96737

The button element may contain elements that are phrasing content without also being interactive content. In other words: elements that get used on the intra-paragraph level (sometimes called inline elements), and that don’t allow user interaction.

For example, this means it may contain span elements, but not div elements. So this is valid:

<button>
  <span>'hi'</span>
</button>

Upvotes: 2

Tigger
Tigger

Reputation: 9130

Nested tags within a <button> is not valid and returns the following when tested:

Element div not allowed as child of element button in this context.

Non-nested tags is the correct way to go.

See for your self if you like. I used the follow HTML to test:

<!DOCTYPE html>
<html lang="en"> 
<head> 
<title>Button test HTML</title> 
</head>
<body>
<button>
<div>
   <span>'not valid'</span>
 </div>
</button>
<button>Valid</button>
</body>
</html>

Upvotes: 2

omri_saadon
omri_saadon

Reputation: 10669

Basically the specification does not allow that.

It might work for you but it's not the best practice.

As you can see here button must be no interactive content descendant.

You also can verify your html in here

Upvotes: 2

Related Questions