当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


HTML DOM Section用法及代码示例


HTML DOM中的Section对象用于表示HTML <section>元素。可以使用getElementById()方法访问section元素。

用法:

document.getElementById("id")

将id分配给<section>标签的位置。

范例1:

<!DOCTYPE html>  
<html>  
    <head> 
        <title> 
            HTML DOM section Object 
        </title> 
    </head> 
      
    <body style = "text-align:center;">  
  
        <h1 style = "color:green;" >  
            GeeksForGeeks  
        </h1>  
          
        <h2>DOM section Object</h2>  
          
        <button onclick = "Geeks()"> 
            Click Here 
        </button> 
          
        <br><br> 
  
        <section id = "sec"> 
            A computer science portal for geeks. 
        </section> 
          
        <script> 
            function Geeks() { 
                var txt = document.getElementById("sec"); 
                txt.style.color = "green"; 
            } 
        </script> 
    </body>  
</html>                    

输出:
在单击按钮之前:
section
单击按钮后:
section



范例2:可以使用document.createElement方法创建Section对象。

<!DOCTYPE html>  
<html>  
    <head> 
        <title> 
            HTML DOM section Object 
        </title> 
    </head> 
      
    <body>  
        <h1 style = "color:green;" >  
            GeeksForGeeks  
        </h1>  
          
        <h2>DOM section Object</h2>  
  
        <button onclick = "Geeks()"> 
            Click Here! 
        </button><br> 
          
        <script> 
            function Geeks() { 
                var x = document.createElement("SECTION"); 
                x.setAttribute("id", "sec"); 
                document.body.appendChild(x); 
                  
                var para = document.createElement("H5"); 
                var txt = document.createTextNode("This" 
                    " text belongs to section."); 
                para.appendChild(txt); 
                document.getElementById("sec").appendChild(para); 
            } 
        </script> 
</body>  
</html>                    

输出:
在单击按钮之前:
section
单击按钮后:
section





注:本文由纯净天空筛选整理自GeeksforGeeks大神的英文原创作品 HTML | DOM Section Object。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。