Home  >  Article  >  Web Front-end  >  How to append HTML code to a div using JavaScript?

How to append HTML code to a div using JavaScript?

王林
王林forward
2023-09-06 12:09:02772browse

如何使用 JavaScript 将 HTML 代码附加到 div?

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.

method

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>';

explain

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

Example

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

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete