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

How to Dynamically Change Div Content Using JavaScript?

Patricia Arquette
Release: 2024-10-31 09:08:30
Original
227 people have browsed it

How to Dynamically Change Div Content Using JavaScript?

Dynamically Modifying Div Content Using JavaScript

Altering the content of a div element with JavaScript can be achieved with an intuitive approach. The following HTML code snippet serves as an example:

<code class="html"><html>
  <head>
    <script>
      function changeDivContent() { /* ... */ }
    </script>
  </head>
  <body>
    <input type="radio" name="radiobutton" value="A" onClick="changeDivContent()">
    <input type="radio" name="radiobutton" value="B" onClick="changeDivContent()">
    <div id="content"></div>
  </body>
</html></code>
Copy after login

Within this example, the objective is to modify the inner HTML content of div#content based on the user's selection of radio buttons with values "A" or "B." However, the div element lacks a JavaScript attribute "value" to facilitate this action.

To address this, JavaScript provides a straightforward solution by utilizing the innerHTML property of the HTML element. By implementing the following code:

<code class="js">document.getElementById("content").innerHTML = "whatever";</code>
Copy after login

within the changeDivContent() function, you can dynamically set the content of div#content to any desired value. This enables you to seamlessly update the content of a div element based on user input or other dynamic conditions within your JavaScript code.

The above is the detailed content of How to Dynamically Change Div Content Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
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!