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;
Advertisement
Answer
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.