DOM in JavaScript

In JavaScript DOM is used to update, edit and delete elements and attributes.

DOM is created automatically when it webpages are loaded on a web browser.

It used to add dynamic content to our web pages.

Methods used in DOM:

write(“string”)

It used to write given string on the document.

writeln(“string”)

It used to write given string on the document with a newline character at the end.

getElementById()

Returns the element having the given id value.

getElementByName()

In this name is used at the place of id

getElementByTagName()

It used to count the total number of paragraph used in the code.

getElementByClassName()

In this, we will find element by class name.

Syntax to write DOM object:

document.form1.name.value 

where form1 is form name. name is input text name and value defines a value of input text.

getElementById()- returns the element of specified id.

Ex.

<!DOCTYPE html> 

<html> 

    <head> 

        <title>

            DOM

        </title> 

        <script>

        // Function

        function hello() {

            var demo = document.getElementById("id");

            demo.style.color = "blue";

        } 

        </script> 

    </head> 

     <body>

        <h1 id = "id">codersarts</h1>

        <input type = "button" onclick = "hello()"

            value = "Click here" />

    </body> 

</html>

getElementByName():

 

<script type="text/javascript">  

function elements()  

    {  

       var gen=document.getElementsByName("gender");  

       alert("Total Genders:"+gen.length);  

 } 

</script>

 

  <from> {

        Male:<input type="radio" name="gender" value="male">

        <input type="button" onclick="elements()" value="Genders">  

  </form> 

 

 

 }

getElementByTagName():

Used to count number of paragraph in the documents.

Ex.

<script type="text/javascript"> 

      function count2(){ 

         var totalh2=document.getElementsByTagName("h2"); 

         alert("total h2 tags are: "+totalh2.length); 

 } 

      function count3(){ 

         var totalh3=document.getElementsByTagName("h3"); 

         alert("total h3 tags are: "+totalh3.length); 

 } 

</script> 

      <h2>This is h2 tag</h2> 

      <h2>This is h2 tag</h2> 

       <h3>This is h3 tag</h3>   

       <button onclick="count2()">count h2</button> 

       <button onclick="count3()">count h3</button>

      .InnerHTML: This property used to create dynamic HTML web page like registration etc.

<html>

    <body>

         <script type="text/javascript" > 

function fun() { 

        var data="Name:<br><input type='text' name='name'><br><input type='submit' value='comment'>"; 

 

        document.getElementById('id1').innerHTML=data; 

 } 

 

</script> 

<form name="form1"> 

      <input type="button" value="click here for comments" onclick="fun()"> 

      <div id="id1"></div> 

</form> 

</body>

</html>

Powered  by Codersarts