Setting a unique identifier for a newly created element in JavaScript and the DOM

Is there a way to assign an element ID to a newly created element using JavaScript DOM?

The code I've written generates a table that is displayed when a button is clicked.

I'm looking to give this table a unique ID so it can have a distinct style from other tables on my website.

Below is an example of the code I've written:

var tab = document.createElement("ViewShoppingCart");
document.getElementById("shopping_list").appendChild(tab);

var tbdy = document.createElement("tbody");
tab.id = "new_cart";
tab.appendChild(tbdy);
new_cart = true;

var total = 0;

for (var a = 0; a <= nameArray.length-1; a++) {

var tr = document.createElement("tr");
tbdy.appendChild(tr);

var td = document.createElement("td");
    td.appendChild(document.createTextNode("x " + quantityArray[a]));
    tr.appendChild(td); 

var td2 = document.createElement("td");
    td2.appendChild(document.createTextNode(nameArray[a]));
    tr.appendChild(td2);

var td3 = document.createElement("td");
    td3.appendChild(document.createTextNode(sumArray[a]));
    tr.appendChild(td3);

}

Answer №1

Experiment

let tableBody = document.createElement("tbody");
tableBody.id = "dynamicTableBody";
table.id = "shoppingCart";
table.appendChild(tableBody);
shoppingCartActive = true;

Answer №2

When it comes to styling elements, it's best to utilize class selectors over IDs.

Additionally, avoid using duplicate IDs in your HTML as it can diminish the effectiveness of CSS styles, especially when working with table content.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to remove the black border on a material-ui button

I am currently working with the material-ui datepicker and buttons. Whenever I click on the datepicker icon to select a date or any of the buttons, I notice a black border appearing. How can I remove this black border from the design? ...

How do I extract elements from an array?

I'm working with an array of objects: var aoo = [{},{},{},....{},{},{}]; I am looking for an efficient function that can retrieve elements from index n to m. For example: var getEl = function(from, to) { ... return array } What is the best way to ...

Is the Spring MVC ModelAndView object being returned?

After clicking a link on a jsp page, I have a GET method that is instantiated as: HTML: <div class="panel accordion clearfix" id="dispdir"> <script type="text/javascript"> window.onload = function() { //showDirectorySe ...

Techniques for retrieving elements from HTML using jQuery

I'm developing a feature that allows users to add videos to playlists by clicking on a link in a popover. The challenge I'm facing is extracting the video_id and the selected playlist when the user interacts with the popover. Any tips on how to a ...

Retain selected elements and eliminate the rest while maintaining structure with Cheerio/jQuery

I am looking to isolate specific elements while maintaining their structure. For example: <html> <head> <meta xx> </head> <body> <div class="some1"> <div class="some1-1">< ...

Can JSON-formatted JavaScript variables be inserted and utilized in MongoDB?

I am currently in the process of formatting a large JavaScript file so that I can insert it into a MongoDB collection and retrieve it using AJAX. However, I am encountering issues with the syntax. Here is an example snippet: var MyData = [ { Elements: ...

When hovering over various div elements in HTML

I've been experimenting with some code lately, and I'm trying to change the text color of a menu element when hovering over it. I can alter the background color just fine, but for some reason, the text color remains unchanged. Can anyone offer a ...

Creating various visualizations using React

I am new to React, Highcharts, and UI development in general. My goal is to render multiple charts from an array of data. However, I'm currently facing an issue where only the last chart - based on the last data in the array - is displayed on the page ...

Error: Expecting only one React element child to be passed into React.Children.only() function

I am encountering an issue while attempting to construct a web table using the antd library. The exact error message reads: "react.development.js:1251 Uncaught Error: React.Children.only expected to receive a single React element child". I have been stru ...

Conceal part of the page initially, then reveal it when clicked

After integrating Rails 3 and JQuery, I encountered an issue where a div containing a rendered partial would not hide when attempting to do so using JQuery in my JavaScript. I want to be able to hide the div initially, then show it upon clicking a button. ...

Ensuring Sequential AJAX Calls in jQuery for Optimal Performance

I recently transitioned some code to FastCGI for backend processing of AJAX requests from a jQuery-driven front end. While FastCGI has generally sped up the process, I've encountered a performance drawback when two jQuery AJAX requests are made in rap ...

Error: Authorization token is required

For email confirmation, I am utilizing JWT. An email is sent to the user with a URL containing the token. Here's an example of the URL received by the user: http://localhost:3000/firstlogin?acces_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI ...

Decode a JavaScript string without the need to save it as a file

Imagine a situation where I allow a client to input a JavaScript script that needs to be sent to my server. This script is meant to export an object. Here is the frontend code snippet: <form action="/blabla.js" method="post"> ...

Dimming the background of my page as the Loader makes its grand entrance

Currently, I am in the process of developing a filtering system for my content. The setup involves displaying a loader in the center of the screen whenever a filter option is clicked, followed by sorting and displaying the results using JQuery. I have a v ...

Exploring methods to trace the factory's property that is receiving updates from another factory within AngularJS

Hey there, I'm new to Angularjs and I have a bunch of factories in my application. The situation is, let's say we have obj1 in factoryA. Whenever I console.log(obj1), it displays numerous properties associated with it. This object is being update ...

Sending values to URL using the <a> tag in HTML

I currently have the selected language stored in a variable (var lan= urlParam('language')). I am trying to pass this language as a parameter (without PHP) in a URL within an "a" tag, like so: <a href="http://hotelscombined.sitewish.gr/HotelN ...

What is the process for adjusting the input value dynamically in reactjs?

I am working on a dynamic time input row and I need to ensure that the values are updated correctly. This is the code snippet I am using: https://codesandbox.io/s/624vq8y7y3 When I run the code, the values in the TimeInput field do not change as expected ...

Prevent running function bodies simultaneously based on user events in JavaScript until a previously triggered execution is completed

When a user clicks on a button in my component, the doSomething function is activated. The issue I am facing is that doSomething takes between 200-1100ms to finish execution and change state. What complicates matters is that when the button is clicked rapi ...

Refresh the table dynamically in Django without the need to reload the entire page

Seeking assistance to update a small table with new data every 10 seconds on a Django website. The data is parsed into JSON and refreshed in the database, then displayed on the front-end. Looking for help with writing AJAX code to continuously refresh the ...

The framework for structuring web applications using Javascript programming

While I have extensive experience in PHP and C# programming, my knowledge of Javascript is limited. When it comes to server side programming, MVC is my preferred method as it allows me to keep my code well-organized. However, when it comes to writing Java ...