To append HTML code to a div using JavaScript, we first need to select the div element. We can do this by using the document.getElementById() method and passing in the id of the div element. Next, we use the innerHTML property of the div element and set it equal to the HTML code we want to append, preceded by the = operator.
One way to append HTML code to a div using JavaScript is to select the div using its id,
Then add the required HTML code using the innerHTML attribute. For example -
var div = document.getElementById('myDiv'); div.innerHTML += '<p>This is some new HTML code</p>';
In this example, we will use JavaScript to append the HTML code to the div.
First, we will create a div element -
<div id="container"></div>
Next, we will create a function to append the HTML code to the div element -
function appendHtml() { var div = document.getElementById('container'); div.innerHTML += '<p>This is some HTML code</p>'; }
Finally, we will call this function when the page loads -
window.onload = function() { appendHtml(); }
<!DOCTYPE html> <html> <head> <title>Append HTML Code</title> </head> <body> <div id='container'></div> <script> function appendHtml() { var div = document.getElementById('container'); div.innerHTML += '<p style="color:black">This is some HTML code</p>'; } window.onload = appendHtml; </script> </body> </html>
The above is the detailed content of How to append HTML code to a div using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!