SoFunction
Updated on 2025-03-01

JavaScript dynamically creates div attributes and style sample code

1. Create a div element:

Javascript code
Copy the codeThe code is as follows:

<scripttypescripttype="text/javascript">
functioncreateElement(){
varcreateDiv=("div");
="Testcreateadivelement!";
(createDiv);
}
</script>

<scripttypescripttype="text/javascript">
functioncreateElement(){
varcreateDiv=("div");
="Testcreateadivelement!";
(createDiv);
(divName); <!-- no "document" if not body-->
}
</script>

2. Create the properties of the div:

Javascript code
Copy the codeThe code is as follows:

<scripttypescripttype="text/javascript">
functioncreateElement(){
varcreateDiv=("div");
="thisisanewdiv.";
="newDivId";
="newDivClass";
="Testcreateadivelement!";
(createDiv);
}
</script>

<scripttypescripttype="text/javascript">
functioncreateElement(){
varcreateDiv=("div");
="thisisanewdiv.";
="newDivId";
="newDivClass";
="Testcreateadivelement!";
(createDiv);
<!--Directly use 2 CSS class styles-->
= "name file_col";
}
</script>

3. Create the style of the div:

Javascript code
Copy the codeThe code is as follows:

<scripttypescripttype="text/javascript">

functioncreateElement(){
varcreateDiv=("div");
="pink";
="1pxsolidred";
="50px";
="50px";
="Testcreateadivelement!";
(createDiv);
}
</script>