[javascript] add id to dynamically created <div>

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;

This question is related to javascript jquery

The answer is


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);
}

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");

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 ... */

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. :)


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">