javaScript html  dom - Changing HTML Content Attribute

the html dom allows javaScript to change the content of html elements.


changing html content

the innerhtml property provides access to all of the content stored in an element.

you can sets or gets the contents of the html element is by using the innerhtml property.

syntax:

         document.getElementById(id).innerhtml = 'new content'

this example change the content of <p> and <h1> elements:

     <body>
            
              <p id="p"> this is the <em>first</em> paragraph </p>
              
              <h1 id="h"> this is the <em>first</em> heading <h1>
  <script>
             
document.getElementById("p").innerhtml = "this is the innerhtml data p" ;
                        
document.getElementById("h").innerhtml = "this is the heading html data" ;
                        
          </script>              
          
   <body>

changing an html attribute

if you want to change the attribute value of an html element, use this syntax:

    document.getElementById(id).attributeName= "value" 

look this example change the width, height, src attributes value of an <img> element:

  <!doctype html>
  
     <head>  <title> change attribute value </title>
   
   <script>
      
              function    changeattr(){
              
                          var   o = document.getElementById("im");
                          
                          o.src ="/images/goldentree.jpg";
                          
                          o.width ="300";
                          
                          o.height="300";
              }
  </script>   </head>
         
           <body>
           
<img   id='im' src='/images/year.gpj' width='200px' height='200px'>
             
<button onclick="changeattr()">click here to change attribute value</button>
             
         </body>    

  </html>