How to create links to sections within the same page in HTML ? - GeeksforGeeks (2024)

Skip to content

  • Courses
    • Newly Launched!
    • For Working Professionals
    • For Students
    • GATE Exam Courses
  • Tutorials
    • Data Structures & Algorithms
      • Data Structures
        • Tree
  • HTML Tutorial
  • HTML Exercises
  • HTML Tags
  • HTML Attributes
  • Global Attributes
  • Event Attributes
  • HTML Interview Questions
  • HTML DOM
  • DOM Audio/Video
  • HTML 5
  • HTML Examples
  • Color Picker
  • A to Z Guide
  • HTML Formatter

Open In App

Suggest changes

Like Article

Like

Save

Report

We will explore how to create links within an HTML page that are linked to specific sections of the same page. Creating internal links in HTML enhances user experience by making navigation easier for website visitors. By using the id attribute and the <a> (anchor) tag, you can link to specific sections of a webpage, allowing quick access to needed information without scrolling through the entire page.

Syntax:

<a href="#section1" >section 1</a>

Approach

  • Use the Anchor Tag <a>: In HTML, use the <a> tag to create links within the same page.
  • Assign Unique IDs: Assign unique IDs to different sections of the webpage using the id attribute.
  • Set the href Attribute: Set the href attribute of the anchor tag to “#section1” (replace “section1” with the desired ID) to link to a specific section.
  • Avoid Using Class Names in href: Class names are not unique identifiers and should not be used in the href attribute for internal linking.

Example: Below is an example where we divide the webpage into sections using <div>, assign unique IDs to each section, and use <a> tags in the navigation section with href=”#section1″ to enable users to navigate to specific sections with a click.

HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Section links</title> <style> * { margin: 0; padding: 0; } body { width: 100vw; height: 100vh; } .section { width: 100vw; height: 40vh; background-color: #EF5354; font-size: 50px; color: white; text-align: center; margin: 10px 5px; } .one, .three { background-color: #E03B8B; } .nav { width: 100vw; height: 40vh; background-color: #3944F7; font-size: x-large; color: white; text-align: center; margin: 10px 5px; display: flex; flex-direction: row; justify-content: space-around; place-items: center; } .btn { color: white; background-color: #38CC77; height: 40px; width: 90px; padding: 2px; border: 2px solid black; text-decoration: none; } </style></head><body> <div class="nav"> <a href="#section1" class="btn">1</a> <a href="#section2" class="btn">2</a> <a href="#section3" class="btn">3</a> <a href="#section4" class="btn">4</a> </div> <div class="section one" id="section1"> section 1 </div> <div class="section two" id="section2"> section 2 </div> <div class="section three" id="section3"> section 3 </div> <div class="section four" id="section4"> section 4 </div></body></html>

Output:


Creating internal links in HTML is a simple yet good way to improve website navigation and user experience. By using the id attribute and the <a> tag, you can create links that direct users to specific sections of a webpage, making it easier for them to find the information they need.



J

jymnjogiya

How to create links to sections within the same page in HTML ? - GeeksforGeeks (3)

Improve

Next Article

How to Create Links to Other Pages in HTML ?

Please Login to comment...

Similar Reads

How to define a number sections and sub-sections with section in CSS ? In this article, we will learn how to define a number of sections and sub-sections with the section in CSS. The section tag defines the section of documents such as chapters, headers, footers, or any other sections. The section tag divides the content into sections and subsections. Counters in CSS are basically variables that can be used for number 2 min read How to fetch only sections of specific HTML areas from an external page using AJAX ? In this article, we will see how to fetch the specific sections of an HTML file from an external page using AJAX, along with understanding their basic implementation through the illustrations. Suppose we have an HTML page and this page contains different sections. Each Section can be identified using the class name or ID. Our task is to use Ajax in 4 min read Difference between normal links and active links Websites are designed to point you to different resources. You can move from one website to another through links. Links help you to get information from different resources. Links are established in simple HTML web pages through <a> tag.Links are categorized into three types. Typically a Link is displayed in three different colors based on t 2 min read How to select all links within a Paragraph using CSS? To style all links within a paragraph using CSS, you can use a simple selector. The following code selects all anchors (a) elements that are descendants of paragraph (p) elements. This rule allows you to apply specific styles, such as color and text decoration, exclusively to links within paragraphs, offering a targeted and efficient way to customi 1 min read How to create horizontal scrollable sections using CSS ? In this article, we will see how we can create a horizontal scrollable section using CSS. We are going to make different sections and make them horizontally scrollable using CSS. HTML code is used to create the basic structure of the sections and CSS code is used to set the style. HTML Code: In this section, we will create a structure for our secti 3 min read How to display search result of another page on same page using ajax in JSP? In this example, we are creating a search bar to display the result on the same page in using ajax in JSP. AJAX stands for Asynchronous JavaScript and XML. Where Ajax is mainly used for Displaying another web page content on the same web page without refreshment of the page. You can read more about ajax technology here. Approach: We use the JQuery 2 min read How to separate Handlebars HTML into multiple files / sections using Node.js ? In this article, we will learn about separating Handlebars HTML into multiple files/sections using Node.js and using it on any page that you want. It helps in reducing the repetition of code. For example, instead of adding the whole navbar on each page, you can just make a template of that navbar and, use import it to any page you want. We can make 3 min read Open all persons solution links from submission page using JavaScript JavaScript is a high-level, interpreted programming language that conforms to the ECMAScript specification. jQuery is a JavaScript library designed to simplify HTML DOM tree traversal and manipulation. Example: Step 1: Open any geeksforgeeks solution page. Open the page in inspect mode by pressing F12 or through inspect option.step 2: Now copy and 2 min read How to create Right Aligned Menu Links using HTML and CSS ? The right-aligned menu links are used on many websites. Like hotels website that contains lots of options in the menu section but in case of emergency to make contact with them need specific attention. In that case, you can put all the menu options on the left side of the navigation bar and display contact us option on the right side of the bar. Th 3 min read How to create animated banner links using HTML and CSS? Links are one of the most important parts of any component that is used in website making. Almost every component had some form of links in it. A common example is a menu/nav-bar. All we see is some button like home, about, etc. but under the hood they all are links. Sometimes there comes a situation where you don't want to wrap the link inside a b 2 min read How to Create Links to Other Pages in HTML ? HTML links are like pathways on the internet. They connect one webpage to another. Imagine a link as having two parts: a starting point (where you click) and an endpoint (where you end up). When you click on a link, you're basically starting at one point (the anchor) and moving to another (the destination). These links are made using anchor tags in 2 min read Angular PrimeNG Table Sections Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. This article will show us how to use Table Column Grouping in Angular PrimeNG. Angular PrimeNG Table Sections offer various templates to display addit 5 min read Angular PrimeNG TreeTable Sections Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. It provides a lot of templates, components, theme design, an extensive icon library, and much more. In this article, we are going to learn Angular Pri 6 min read Angular PrimeNG Tree Sections Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. This article will show us how to use Tree Sections in Angular PrimeNG. Angular PrimeNG Tree Sections offer various templates to display additional inf 4 min read XML - CDATA Sections CDATA sections are a mechanism in XML for handling character data that might otherwise be misinterpreted by the XML parser. CDATA stands for Character Data. These sections include blocks of text within an XML document that the parser should treat literally, without interpreting any characters as XML markup. This is helpful when the text contains ch 2 min read How to redirect a page to another page in HTML ? Redirecting a page in HTML involves sending users to a different web page automatically or upon interaction. This can be achieved using the anchor tag's href attribute or the meta tag with the http-equiv attribute set to refresh and the content attribute specifying the time delay and destination URL. Understanding these methods helps improve naviga 3 min read How to Create Nested tables within tables in HTML ? HTML tables are very helpful in structuring the content in the form of rows and columns. But sometimes there is a need to add a table within a table. HTML supports this functionality and is known as the nesting of the tables. Tables can be nested together to create a table inside a table. To create a nested table, we need to create a table using th 3 min read How will you access the reference to same object within the object in PHP ? In this article, we will see how we can access the reference to the same object within that object in PHP. To do that we have to use the "$this" keyword provided by PHP. PHP $this Keyword: It is used to refer to the current objectIt can only be used inside the internal methods of the class.$this keyword can refer to another object only if it is ins 2 min read How to Create Navigation Links using HTML5 ? In this article, we create a navigation link by using the <nav> tag in the document. The nav element represents a section of the page whose purpose is to provide navigational links, either in the current document or to other documents. The links in the "nav" element may point to other webpages or to different sections of the same webpage. It 1 min read How to create links with 'target="_blank"' in Markdown ? In this article, we will see how to create links with 'target="_blank"' in Markdown. Markdown is a free and open-source lightweight markup language that can be utilized to include formatting elements to plaintext text documents. It is a special way to write words that makes them look different on a computer. For instance, you can make some words lo 4 min read How to create lists and links using jQuery EasyUI Mobile ? In this article we will learn how to design lists, group them and create links for easy navigation using jQuery EasyUI Mobile. EasyUI is a HTML5 framework for using user interface components based on jQuery, React, Angular and Vue technologies. It helps in building features for interactive web and mobile applications saving a lot of time for develo 4 min read HTML DOM links Collection The DOM links collection is used to return the collection of all <a> and <area> elements with the "href" attribute in the HTML document. The elements in the collection are sorted as they appear in the sourcecode. Syntax: document.links Properties: It contains a single property length which is used to return the number of <a> and 4 min read How to disable HTML links using JavaScript / jQuery ? Given an HTML link and the task is to disable the link by using JavaScript/jQuery. Approach 1: Disable HTML link using JavaScript using setAttribute() Method. JavaScript setAttribute() Method: This method adds the defined attribute to an element and gives it to the passed value. In case of the specified attribute already exists, the value is set/ch 5 min read How to Add Skip Navigation Links for Better Web Accessibility in HTML? Adding skip navigation links in HTML is an essential practice for enhancing web accessibility. These links allow users to bypass repetitive navigation menus and directly access the main content of a webpage, especially for screen reader users or keyboard-only users. This simple addition significantly improves the usability and accessibility of a we 7 min read How to use anchor tag to open links in HTML ? In this article, we will learn how to use anchor tags to open links in HTML and we will implement different operations using anchor tags in HTML. We will see in this article, how to redirect another website through an anchor tag and how to open a blank new tag for any new link to open an image in a new tag, and how to open the image on the same pag 3 min read HTML Links Hyperlinks HTML links, or hyperlinks, connect web pages and are created using the `<a>` tag with the `href` attribute. They enable users to navigate between pages or resources. Links can be text, images, or other elements, enhancing web navigation and interactivity. Users can click on links to navigate between different pages or resources. Note: A hyper 3 min read How can a page be forced to load another page in JavaScript ? In JavaScript, you can force a page to load another page by using the window.location object. There are a few methods to achieve this. To force a page to load another page in JavaScript, we have multiple approaches: Below are the approaches used to force a page to load another page in JavaScript: Table of Content Using window.location.replaceUsing 2 min read How to show Page Loading div until the page has finished loading? There are a lot of ways in which we can show a loading div but we have figured out the most optimal solution for you and that too in pure vanilla JavaScript. We will use the document.readyState property. When the value of this property changes, a readystatechange event fires on the document object. The document.readyState property can return these 2 min read How to create a form within dropdown menu using Bootstrap ? A Dropdown menu is used to allow the user to choose the content from the menu as per their requirement and it is used to save screen space and avoid the long scrolling of the web pages. In web design, we often come in a scenario where we need to create a form within the dropdown menu to get some user data or to give access to specific content. Prer 3 min read

Article Tags :

  • HTML
  • Web Technologies
  • HTML-Questions

Trending in News

View More
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • How to Lock Cells in Google Sheets : Step by Step Guide
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

How to create links to sections within the same page in HTML ? - GeeksforGeeks (4)

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `

${comment_text}

`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `

${suggest_val}

`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `

Thank You!

Your suggestions are valuable to us.

You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.

`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('

'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('

'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });

How to create links to sections within the same page in HTML ? - GeeksforGeeks (2024)
Top Articles
Impulse Buying: What It Is and How to Stop
1819 25C MS | Coin Explorer
Noaa Charleston Wv
Froedtert Billing Phone Number
Craigslist Phoenix Cars By Owner Only
Best Cav Commanders Rok
Ap Chem Unit 8 Progress Check Mcq
Caliber Collision Burnsville
Troy Athens Cheer Weebly
Pvschools Infinite Campus
Colts seventh rotation of thin secondary raises concerns on roster evaluation
How to Store Boiled Sweets
Industry Talk: Im Gespräch mit den Machern von Magicseaweed
Luna Lola: The Moon Wolf book by Park Kara
Craigslist Blackshear Ga
Eva Mastromatteo Erie Pa
10-Day Weather Forecast for Santa Cruz, CA - The Weather Channel | weather.com
Ups Access Point Lockers
97226 Zip Code
Craigslist Prescott Az Free Stuff
We Discovered the Best Snow Cone Makers for Carnival-Worthy Desserts
Engineering Beauties Chapter 1
Craigslist Maryland Trucks - By Owner
The Listings Project New York
Globle Answer March 1 2023
TeamNet | Agilio Software
Victory for Belron® company Carglass® Germany and ATU as European Court of Justice defends a fair and level playing field in the automotive aftermarket
Cars & Trucks - By Owner near Kissimmee, FL - craigslist
Carroway Funeral Home Obituaries Lufkin
Bayard Martensen
CohhCarnage - Twitch Streamer Profile & Bio - TopTwitchStreamers
Nikki Catsouras: The Tragic Story Behind The Face And Body Images
Craigslist/Phx
Craigslist Org Sf
Glossytightsglamour
Jennifer Reimold Ex Husband Scott Porter
1v1.LOL Game [Unblocked] | Play Online
A Comprehensive 360 Training Review (2021) — How Good Is It?
Pro-Ject’s T2 Super Phono Turntable Is a Super Performer, and It’s a Super Bargain Too
Sun Tracker Pontoon Wiring Diagram
Quaally.shop
Child care centers take steps to avoid COVID-19 shutdowns; some require masks for kids
Go Nutrients Intestinal Edge Reviews
Www.homedepot .Com
Identogo Manahawkin
Bismarck Mandan Mugshots
Blog Pch
Cvs Minute Clinic Women's Services
Cars & Trucks near Old Forge, PA - craigslist
Used Curio Cabinets For Sale Near Me
Latest Posts
Article information

Author: Gregorio Kreiger

Last Updated:

Views: 6253

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Gregorio Kreiger

Birthday: 1994-12-18

Address: 89212 Tracey Ramp, Sunside, MT 08453-0951

Phone: +9014805370218

Job: Customer Designer

Hobby: Mountain biking, Orienteering, Hiking, Sewing, Backpacking, Mushroom hunting, Backpacking

Introduction: My name is Gregorio Kreiger, I am a tender, brainy, enthusiastic, combative, agreeable, gentle, gentle person who loves writing and wants to share my knowledge and understanding with you.