Just a few days back one of our reader Dhawal asked me on our Sitemap post that how jump within a web-page using # URL without actually loading the page again. A good question indeed. But to answer that we need to go in-depth with HTML nesting and HTML element IDs. Although it is not that much tough to understand, but you need to have a little of patience to understand the concept.
So without haphazardly discussing on this matter we shall start from the very basic thing learning the following items:
- Usage of HTML Ids and how to implement them
- Some other uses of HTML Ids.
So please read on…
Usage of HTML Ids and their Implementation on CSS and JS:
1. How we style up a particular nesting element using CSS:
Suppose our HTML nesting of a particular web-page is something like this:
Now we want to style up the div element having id “nesting-1” using CSS. Then we need to write the CSS part like this:
Take a look at the following code:
Just paste the code in a notepad file and save as abc.html. Open up the file using Firefox and click on the Click here to change the last list element button. You should see that the last list item’s value got changed from “The last item of this list” to “So this is going to my value”. Now let us see how this thing has worked!
- First take a deeper look to the JS code. Here we have defined a function named “change” which is:
- So when this function is executed this will search the document to get the HTML element having the specified id. Then it will change the innerHTMl of that element to the value which we have specified through the argument of that function.
- Lets now take a look on the following code:
Now this anchor element when clicked executes the function giving the arguments “So this is going to my value” and “changing”. Which means this will execute the JS function to search for the HTML element having id “changing” (here the <li> tag) and will change its innerHTML to “So this is going to my value”
So from the above discussion we have learned how id of an HTML element can be used as:
How about having a quick look at the w3c.org for a detailed info this?
This is it for this tutorial. On the next part we shall see how we can use the Id of a particular wrapping/nesting part of the web-page to jump to that portion using #. Also we shall discus on creating the custom jump elements using Ids.