當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


HTML DOM BR用法及代碼示例


DOM BR對象用於表示HTML <br>元素。 br元素由getElementById()訪問。

用法:

getElementById(id)

其中“id”是分配給br標簽的ID。

示例1:

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>br Tag</title> 
    <style> 
        body { 
            text-align:center; 
        } 
          
        h1 { 
            color:green; 
        } 
    </style> 
</head> 
  
<body> 
    <h1>GeeksforGeeks</h1> 
    <h2>DOM br Object</h2> 
  
    <!-- br tag is used here -->
    <p>GeeksforGeeks:
        <br id="GFG"> Computer science portal</p> 
    <button onclick="myGeeks()">Subnit</button> 
    <script> 
        function myGeeks() { 
            var w = document.getElementById("GFG"); 
            w.style.display = "none"; 
        } 
    </script> 
</body> 
  
</html>

輸出:



在單擊按鈕之前:

單擊按鈕後:

示例-2:可以使用document.createElement方法創建對象。

<!DOCTYPE html> 
<html> 
  
<body> 
    <center> 
        <h1>GeeksForGeeks</h1> 
        <h2>DOM BR Object</h2> 
        <button onclick="Geeks()" style="margin-bottom:20px;"> 
          Submit 
        </button> 
  
        <div id="GFG"> 
            <span>Hello, </span> 
            <span>Geeks.</span> 
            <span>For</span> 
            <span>Geeks</span> 
        </div> 
  
        <script> 
            function Geeks() { 
                <!-- Get the div element with id="GFG" -->
                var g = document.getElementById("GFG"); 
  
                <!-- Get all span elements inside of div. -->
                var f = g.getElementsByTagName("SPAN"); 
  
                <!-- Create a loop which will insert a br 
                     element before each span element in div,  
                     starting from the second span element. -->
                         
                var j; 
                for (j = 1; j < f.length; j++) { 
                    var w = document.createElement("BR"); 
                    g.insertBefore(w, f[j]); 
                } 
            } 
        </script> 
  </center> 
  
</body> 
  
</html>

輸出:

在單擊按鈕之前:

單擊按鈕後:

支持的瀏覽器:下麵列出了DOM Br Object支持的瀏覽器:

  • 穀歌瀏覽器
  • IE瀏覽器
  • Firefox
  • Opera
  • Safari

相關用法


注:本文由純淨天空篩選整理自ManasChhabra2大神的英文原創作品 HTML | DOM BR Object。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。