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


HTML DOM OptionGroup用法及代碼示例


HTML DOM中的OptionGroup對象用於表示HTML <optgroup>元素。可以使用getElementById()方法訪問<optgroup>元素。

屬性值:該對象包含以下列出的兩個屬性值:

  • disabled:它用於設置或返回是否禁用option-group元素。
  • label:它用於設置或返回option-group元素的label屬性的值。

用法:

document.getElementById("ID");

ID分配給<optgroup>元素的位置。

範例1:



<!DOCTYPE html>  
<html>  
    <head>  
        <title> 
            HTML DOM Optgroup Object 
        </title>  
    </head>  
      
    <body style = "text-align:center;">  
      
        <h1 style = "color:green;"> 
            GeeksforGeeks 
        </h1>  
          
        <div> 
            A computer science portal for geeks  
        </div>  
          
        <h2>DOM OptionGroup Object</h2>  
          
        <select>  
            <optgroup id = "GFG" label = "Programming Languages">  
                <option value = "C">C</option>  
                <option value = "C++">C++</option>  
                <option value = "Java">Java</optgroup>  
        </select>  
          
        <br><br> 
          
        <button onclick = "Geeks()"> 
            Submit 
        </button> 
          
        <p id = "sudo"></p> 
          
        <script> 
            function Geeks() { 
                var txt = document.getElementById("GFG").label; 
                document.getElementById("sudo").innerHTML = txt; 
            } 
        </script> 
    </body>  
</html>                                  

輸出:
在點擊按鈕之前:

單擊按鈕後:

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

<!DOCTYPE html>  
<html>  
    <head>  
        <title> 
            HTML DOM Optgroup Object 
        </title>  
    </head>  
      
    <body>  
        <h2>GeeksforGeeks</h1>  
          
        <h2>DOM OptionGroup Object</h2>  
          
        <select id = "GFG">  
            <option value = "C">C</option>  
            <option value = "C++">C++</option>  
            <option value = "Java">Java</optgroup>  
        </select>  
          
        <br><br> 
          
        <button onclick = "Geeks()"> 
            Submit 
        </button> 
          
        <script> 
            function Geeks() { 
                var g = document.getElementById("GFG"); 
                  
                var f = document.createElement("OPTGROUP"); 
                  
                f.setAttribute("label",  
                            "Object Oriented Programming"); 
                              
                f.appendChild(g.options[1]); 
                  
                g.insertBefore(f, g.options[1]); 
            } 
        </script> 
    </body>  
</html>                                 

輸出:
在單擊按鈕之前:

單擊按鈕後:

支持的瀏覽器:下麵列出了DOM OptionGroup對象支持的瀏覽器:

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




相關用法


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