Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to put the id attribute in a "a" tag or in the "h1/h2" tag?

Tags:

html

tags

I'm learning html in w3 school website and I'm at the "html link" chapter. What I don't understand is why they propose using the id attribute in the link tag instead of the heading tag.

Their example:

<p> 
<a href="#C4">See also Chapter 4.</a>
</p>

<h2><a id="C4">Chapter 4</a></h2> 
<p>This chapter explains ba bla bla</p>

My try:

<p>
<a href="#C4">See also Chapter 4.</a>
</p>

<h2 id="C4">Chapter 4</h2>
<p>This chapter explains ba bla bla</p>

Both work the same when I try them but my try take less writing. Is there something wrong in my try that I don't understand.

like image 718
Francis Dumas Avatar asked Dec 20 '22 16:12

Francis Dumas


1 Answers

It often seems something of a well-kept secret that you can anchor link to elements by their ID, rather than, as more usually, an a tag via its name attribute. This is probably because the former was a later introduction, and so the a tag approach used to be the only means of internal linkage.

So yes, your approach is perfectly valid.

W3SChools, incidentally, while undoubtedly useful at times, has come under fire for some less than solid content over the years. Do not treat it as gospel - it is not affiliated with the W3C, it's just someone's attempt to teach web dev.

Finally, don't confuse head*er* tags with head*ing* tags; in your case it's heading, not header. That's a different tag entirely.

like image 118
Mitya Avatar answered Jan 13 '23 17:01

Mitya