Home > Web Front-end > JS Tutorial > body text

How to append HTML code to a div using JavaScript?

王林
Release: 2023-09-06 12:09:02
forward
796 people have browsed it

如何使用 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>';
Copy after login

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>
Copy after login
  • 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>';
}
Copy after login
  • Finally, we will call this function when the page loads -

window.onload = function() {
   appendHtml();
}
Copy after login

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>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!