Skip to content
Advertisement

add id to dynamically created

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.

JavaScript

Advertisement

Answer

If I got you correctly, it is as easy as

JavaScript

No need for jQuery.

Have a look at the properties of a DOM Element.

For classes it is the same:

JavaScript

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement