add id to dynamically created <div>

JavascriptJquery

Javascript Problem Overview


I have the following JavaScript that creates a div and then appends it to the body and then inserts some dynamically generated HTML into it. cartDiv = document.createElement('div'); This div I would like to add an id and/or a class to it. If possible both Jquery and JavaScript answers would be great.

var cartHTML = '<div class="soft_add_wrapper" onmouseover="setTimer();">';
cartHTML += '<div class="soft_add_header_shadow">';
cartHTML += '<div class="soft_add_header"><span class="soft_add_span">Added to cart</span><a href="" class="close_btn" onclick="hideCart(); return false;">Close</a></div></div>'
cartHTML += '<div class="soft_add_content_shadow"><div class="soft_add_content_wrapper">';
cartHTML += '<div class="soft_add_content_area" onscroll="setTimer();"><table class="cart_table" cellpadding="0" cellspacing="0" border="0">';
if (cartLength != 0) {
	cartHTML += cartLoop(index, cartLength);
	if (index != 0) {
		cartHTML += cartLoop(0, index);
	}
	if (discountTotal != "0") {
		var discountProduct = {
		ProductName: "Discount(s)",
		ProductPrice: '<span style="color:red">' + discountTotal + '</span>'
		}
		cartHTML += getLineItemHTML(discountProduct);
	}
}
cartHTML += '</table></div><div class="soft_add_sub_total"><div class="number_of_items">' + quantity + ' items in cart</div>';
cartHTML += '<div class="sub_total">';
cartHTML += 'Subtotal: <span class="sub_total_amount">' + cartTotal + '</span>';
cartHTML += '</div>';
 cartHTML += '</div><div class="soft_add_action_area"><a href="/ShoppingCart.asp" class="check_out">Check Out</a>';
cartHTML += '<a href="" class="continue_shopping" onclick="hideCart(); return false;">Continue shopping</a></div></div></div></div>';
if (cartDiv == null) {
	cartDiv = document.createElement('div');
	document.body.appendChild(cartDiv);
}
cartDiv.innerHTML = cartHTML;

Javascript Solutions


Solution 1 - Javascript

If I got you correctly, it is as easy as

cartDiv.id = "someID";

No need for jQuery.

Have a look at the properties of a DOM Element.

For classes it is the same:

cartDiv.className = "classes here";

But note that this will overwrite already existing class names. If you want to add and remove classes dynamically, you either have to use jQuery or write your own function that does some string replacement.

Solution 2 - Javascript

You can add the id="MyID123" at the start of the cartHTML text appends.

The first line would therefore be:

var cartHTML = '<div id="MyID123" class="soft_add_wrapper" onmouseover="setTimer();">';

-OR-

If you want the ID to be in a variable, then something like this:

    var MyIDvariable = "MyID123";
    var cartHTML = '<div id="'+MyIDvariable+'" class="soft_add_wrapper" onmouseover="setTimer();">';
/* ... the rest of your code ... */

Solution 3 - Javascript

Just to add another helpful alternative:

  1. create an element:

> const newElement = document.createElement("h3")

  1. give it an id to the newly created element:

> newElement.id = "newElementID";

  1. At this point you can actually print it to your console to see how the element will look like:

> console.log("Printing my new element: ", newElement) > > The result will be: <h3 id="newElementID"></h3>

  1. You can add content to the newly created element,using say innerHTML:

> newElement.innerHTML = "content of new element";

  1. After putting in content, you can select a parent element and append the created element to the parent element:

> parentElement = document.querySelector(".parentElement") > parentElement.appendChild(newElement)

  1. You can even remove the item afterward, if you want, like so:

> newElement.remove();

Solution 4 - Javascript

Not sure if this is the best way, but it works.

if (cartDiv == null) {
    cartDiv = "<div id='unique_id'></div>"; // document.createElement('div');
    document.body.appendChild(cartDiv);
}

Solution 5 - Javascript

Use Jquery for append the value for creating dynamically

eg:

var user_image1='<img src="{@user_image}" class="img-thumbnail" alt="Thumbnail Image" 
style="width:125px; height:125px">';

$("#userphoto").append(user_image1.replace("{@user_image}","http://127.0.0.1:50075/webhdfs/v1/PATH/"+user_image+"?op=OPEN")); 

HTML :

<div id="userphoto">

Solution 6 - Javascript

Here is an example of what I made to created ID's with my JavaScript.

function abs_demo_DemandeEnvoyee_absence(){

	var iDateInitiale = document.getElementById("abs_t_date_JourInitial_absence").value; /* On récupère la date initiale*/
	var iDateFinale = document.getElementById("abs_t_date_JourFinal_absence").value;     /*On récupère la date finale*/
	var sMotif = document.getElementById("abs_txt_motif_absence").value;  				 /*On récupère le motif*/  
	var iCompteurDivNumero = 1;															/*Le compteur est initialisé à 1 parce que la div 1 existe*/
	var TestDivVide = document.getElementById("abs_Autorisation_"+iCompteurDivNumero+"_absence") == undefined; //Boléenne, renvoie false si la div existe déjà
	var NewDivCreation = "";															/*Initialisée en string vide pour concaténation*/
	var NewIdCreation;																	/*Utilisée pour créer l'id d'une div dynamiquement*/
	var NewDivVersHTML;																	/*Utilisée pour insérer la nouvelle div dans le html*/
	
	
	while(TestDivVide == false){														/*Tant que la div pointée existe*/
		iCompteurDivNumero++;															/*On incrémente le compteur de 1*/
		TestDivVide = document.getElementById("abs_Autorisation_"+iCompteurDivNumero+"_absence") == undefined; /*Abs_autorisation_1_ est écrite en dur.*/	
	}
	
	NewIdCreation = "abs_Autorisation_"+iCompteurDivNumero+"_absence"					/*On crée donc la nouvelle ID de DIV*/
	
																						/*On crée la nouvelle DIV avec l'ID précédemment créée*/
	NewDivCreation += "<div class=\"abs_AutorisationsDynamiques_absence\" id=\""+NewIdCreation+"\">Votre demande d'autorisation d'absence du <b>"+iDateInitiale+"</b> au <b>"+iDateFinale+"</b>, pour le motif suivant : <i>\""+sMotif+"\"</i> a bien été <span class=\"abs_CouleurTexteEnvoye_absence\">envoyée</span>.</div>";
	
	document.getElementById("abs_AffichagePanneauDeControle_absence").innerHTML+=NewDivCreation; /*Et on concatenne la nouvelle div créée*/	
	
	document.getElementById("abs_Autorisation_1_absence").style.display = 'none'; /*On cache la première div qui contient le message "vous n'avez pas de demande en attente" */

}
	

Will provide text translation if asked. :)

Solution 7 - Javascript

You'll have to actually USE jQuery to build the div, if you want to write maintainable or usable code.

//create a div
var $newDiv = $('<div>');

//set the id
$newDiv.attr("id","myId");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser357034View Question on Stackoverflow
Solution 1 - JavascriptFelix KlingView Answer on Stackoverflow
Solution 2 - JavascriptPCoughlinView Answer on Stackoverflow
Solution 3 - JavascriptviallyView Answer on Stackoverflow
Solution 4 - JavascriptSandroView Answer on Stackoverflow
Solution 5 - JavascriptPraveen Kumar K RView Answer on Stackoverflow
Solution 6 - JavascriptCorentinView Answer on Stackoverflow
Solution 7 - JavascriptStefan KendallView Answer on Stackoverflow