Skip to content
Related Articles

Related Articles

HTML | DOM Span Object

View Discussion
Improve Article
Save Article
  • Last Updated : 28 Jun, 2021
View Discussion
Improve Article
Save Article

The DOM span object is used to represent the HTML <span> element. The span element can be accessed by using the getElementById() method. 

Syntax: 

document.getElementById("id"); 

Where ‘id’ is the ID assigned to the span tag.
Example-1: In the below program the content inside the span element is accessed and appended to the paragraph element.  

html




<!DOCTYPE html>
<html>
   
<body style = "text-align:center">
        <h1 style = "color:green; font-size:38px;" >
          GeeksForGeeks
        </h1>
 
        <h2>DOM span Object</h2>
         
         
<p>A computer science portal for <span id="span"
        style="color:green;">geeks</span>.</p>
 
         
        <button onclick="Geeks()">Click Here!</button>
         
        <p id="p"></p>
 
         
        <script>
        function Geeks() {
          var x = document.getElementById("span").textContent;
          document.getElementById("p").innerHTML = x;
        }
        </script>
</body>
   
</html>


Output: 
Before clicking on button: 
 

span

After clicking on button: 
 

span

Example-2: Span Object can be created by using the document.createElement method. In the below program, a span object is created on click of the button and a text node is appended to it.  

html




<!DOCTYPE html>
<html>
   
<body>
        <center>
        <h1 style = "color:green;" >
          GeeksForGeeks
        </h1>
        <h2>DOM span Object</h2>
 
        <button onclick="myGeeks()" >Submit</button>
        <br><br>
        <script>
            <!--Creating span element-->
            function myGeeks() {
                var g = document.createElement("SPAN");
                var f = 
                document.createTextNode("A computer science
                portal for geeks.");
   
                g.appendChild(f);
   
                document.body.appendChild(g);
            }
        </script>
</body>
   
</html>


Output: 
Before clicking on button: 
 

span

After clicking on button: 
 

span

Supported Browsers:

  • Google Chrome
  • Mozilla Firefox
  • Edge
  • Safari
  • Opera

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!