Techstacker
Light ModeDark ModeReset dark mode. Falls back to OS dark mode setting.

Pages

No results for 'undefined'

Blog Posts

No results for 'undefined'
Powered by Algolia

How to Add an ID to an HTML Element With JavaScript

Aug 8, 20181 min readJavaScriptViews:

With this neat code snippet you can add an ID attribute to any existing HTML element by using JavaScript.


The Code


let featuredTitle = document.querySelector('h1')
featuredTitle.id = 'featured-title'

Here’s what’s happening in the video:

  • First, we find the h1 element on the web page and assign it to a variable called featuredTitle.
  • Then we attach an ID attribute to that variable via dot notation (variableName.attribute) in this case: featuredTitle.id and give it a value of 'featured-title'.

You can do this to any existing element in the DOM.

Now you can use this dynamically created ID to hook on to either with CSS (to style the element via its new ID) or with JavaScript for handling interactive behavior (like click events).

© 2019 - TechStacker
Powered byGatsbyGithubNetlify