Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to select DOM Elements in JavaScript ?
Next article icon

How to Add an ID to Element in JavaScript ?

Last Updated : 18 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, the ID is the unique identifier through which the elements can be identified and manipulated if required. We can add an ID to an element in JavaScript using various approaches that are explored in this article with practical demonstration.

Below are the possible approaches:

Table of Content

  • Using setAttribute()
  • Using Direct assignment to id property

Using setAttribute()

In this approach, we are using JavaScript's setAttribute() method to dynamically add an ID to an HTML element. Select the element using getElementsByTagName() and then set its ID attribute with the value obtained from user input.

Syntax:

Object.setAttribute(attributename,value)

Example: The below example uses setAttribute() to add an ID to an element in JavaScript.

HTML
<!DOCTYPE html> <html>    <head>     <title>Example 1</title>     <style>         body {             text-align: center;         }          input {             padding: 10px;             margin: 10px;         }     </style> </head>  <body>     <h3>         Using setAttribute()     </h3>     <input type="text" placeholder="Enter ID">     <button onclick="addFn()">         Add ID     </button>     <script>         function addFn() {             const inputEle =                  document.getElementsByTagName('input');             const temp = inputEle[0];             const val = temp.value;             temp.setAttribute('id', val);             alert('ID Added successfully!');         }     </script> </body>  </html> 

Output:

fosiGIF

Using Direct assignment to id property

In this approach, we are using JavaScript's direct assignment to the element's id property to dynamically add an ID. By selecting the element with document.querySelector() and assigning a value to its id property.

Syntax:

Selected_element.id = newID;

Example: The below example uses Direct assignment to id property to add an ID to an element in JavaScript.

HTML
<!DOCTYPE html> <html>    <head>     <title>Example 2</title>     <style>         body {             text-align: center;         }          h1 {             color: green;         }     </style> </head>  <body>     <h3>         Using Direct assignment to          id property     </h3>     <button onclick="addId()">         Add ID to h3     </button>     <script>         function addId() {             const h3Element =                  document.querySelector('h3');             h3Element.id = 'h3ID';             alert('ID added to h3: ' + h1Element.id);         }     </script> </body>  </html> 

Output:

fosiGIF


Next Article
How to select DOM Elements in JavaScript ?

G

gauravggeeksforgeeks
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • How to Select an Element by ID in JavaScript ?
    In JavaScript, we can use the "id" attribute to interact with HTML elements. The "id" attribute in HTML assigns a unique identifier to an element. This uniqueness makes it easy for JavaScript to precisely target and manipulate specific elements on a webpage. Selecting elements by ID helps in dynamic
    2 min read
  • How to Add a Class to DOM Element in JavaScript?
    Adding a class to a DOM (Document Object Model) element in JavaScript is a fundamental task that enables developers to dynamically manipulate the appearance and behavior of web pages. Classes in HTML provide a powerful way to apply CSS styles or JavaScript functionality to multiple elements at once.
    2 min read
  • How to select DOM Elements in JavaScript ?
    Selecting DOM (Document Object Model) elements is a fundamental aspect of web development with JavaScript. It allows developers to interact with and manipulate elements on a webpage dynamically. Proper selection of elements is crucial for tasks such as updating content, adding event listeners, or mo
    3 min read
  • How to Add event listener to Button in JavaScript ?
    In web development adding an event listener to a button is a common task that allows us to execute JavaScript code in response to user interactions, such as clicks. This helps us to create interactive and flexible web pages. Using addEventListener()The addEventListener method is a versatile and wide
    1 min read
  • How to Add JavaScript in HTML Document?
    To add JavaScript in HTML document, several methods can be used. These methods include embedding JavaScript directly within the HTML file or linking an external JavaScript file. Inline JavaScriptYou can write JavaScript code directly inside the HTML element using the onclick, onmouseover, or other e
    4 min read
  • How to create an element from a string in JavaScript ?
    In this article, we will learn how to create an element from a string using JavaScript. This can be used in situations where dynamically generated elements are required by the user. This can be achieved using many approaches as given below: Table of Content Using the createElement() methodUsing the
    3 min read
  • How to Change the ID of Element using JavaScript?
    We are given an element and the task is to change the ID of elements using JavaScript. ID is unique for any element and it can be assigned to an element only once. JavaScript provides a method to access this id and also to manipulate the id. Syntax:Selected_element.id = newID;Below are the appraoche
    3 min read
  • How to Create an Image Element using JavaScript?
    We will dynamically create an <img> element in HTML using JavaScript. When a button is clicked, we'll generate the <img> element and append it to the document. Using createElement() methodCreate an empty img element using document.createElement() method.Then set its attributes like (src,
    1 min read
  • How to dynamically create new elements in JavaScript ?
    New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method. The examples given below would demonstrate this approach. Example 1: In this example, a newly created element is added as a
    3 min read
  • How to Add an Input Field on Button Click in JavaScript ?
    JavaScript allows us to dynamically add an input field upon button click. We can use the below approaches for adding an input field on Button Click in JavaScript. Table of Content Using DOM ManipulationUsing Template Literal and InnerHTMLUsing DOM ManipulationDOM manipulation is used to dynamically
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
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
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences