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

How to append data to an element using JavaScript?

WBOY
Release: 2023-08-27 14:49:09
forward
782 people have browsed it

如何使用 JavaScript 将数据附加到元素?

We can use JavaScript to attach data to the element by adding content to the element using the .innerHTML attribute. This can be done by using the = operator to add new content to the existing content within . We can also add new child elements to using the .appendChild() method.

is a block-level element used to create sections or sections in HTML documents. Elements are typically used to group elements together, such as paragraphs, headings, or images. Elements can also be used to style part of a document, such as adding a background color or border.

method

To append data to a div element using JavaScript, you first need to select the element using a selector and then append the data to the selected element using the append() or appendChild() method.

Here is an example of how to append a paragraph element to a div element -

var div = document.querySelector('div');
var p = document.createElement('p');
p.textContent = 'This is some data that will be appended to the div element';
div.appendChild(p);
Copy after login

Example

Suppose you have a div with an id of "content" -

<!DOCTYPE html>
<html>
<head>
   <title>Append Data to DIV</title>
</head>
   <body>
      <div id='content'>
         <p style='color:black;'>I existed before</p>
      </div>
      <script>
         var div = document.getElementById('content');
         var p = document.createElement('p');
         p.style.color = 'black';
         p.textContent = 'I was appended to the div';
         div.appendChild(p);
      </script>
   </body>
</html>
Copy after login

The above is the detailed content of How to append data to an element 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!