Jump to content
Larry Ullman's Book Forums

Retrieve An Unknown Id Value


Recommended Posts

What is the syntax for specifying the ID attribute of HTML elements - soemthing like 'document.body.id ?
If I wanted to retrieve the 'id=' value of the body element (assuming it is unknown), what statement would handle that?

For example, if each of my pages had a unique ID for the BODY tag, so I can write a common function that does different things depending on which page the user loaded, how would I do this?
 

 

Link to comment
Share on other sites

What is the syntax for specifying the ID attribute of HTML elements - soemthing like 'document.body.id ?

Yes, that's it. You can both read and write the ID attribute of the body element by using document.body.id.

 

You might, for example, write a function in your JS that does something like the following:

switch (document.body.id) {
  
  case 'home':
    
    // The home page. Do something.
    
    break;
    
  case 'about':
    
    // The About Us page. Do something.
    
    break;
    
  case 'site_map':
    
    // The Site Map page. Do something.
    
    break;
    
  default:
    
    // Have a default action.
  
}
  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...