How do you jump to an element by ID via a link in HTML?
To jump to an element by ID via a link in HTML, you need to:
- Assign the element a unique identifier (
id). - In the
<a>link, specify this identifier after the#character in thehrefattribute.
Example:
html
<a href="#section1">Go to section 1</a>
<h2 id="section1">Section 1</h2>
<p>This is the text of the needed section...</p>When the link is clicked, the browser scrolls the page to the element with id="section1".
Navigating to an anchor on another page:
html
<a href="about.html#team">Our team</a>The about.html page must have this element:
html
<h2 id="team">Team</h2>After the click, it navigates to the about.html page and scrolls to the #team block.
You can add smooth scrolling:
To make the transition look smooth, add CSS:
css
html {
scroll-behavior: smooth;
}Conclusion:
To jump to an element by ID, you need to:
- Assign the element an
id, for exampleid="contact". - Create the link
<a href="#contact">To contacts</a>. When clicked, the browser automatically scrolls the page to the element with this ID.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.