簡體   English   中英

使用 JS 更改選擇的第一個選項文本

[英]Change first option text of select with JS

<select>
  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option 3</option>
</select

我想用文本“在此處選擇”替換文本“選項 1”。 僅使用 JS。 但只有選擇的第一個選項。

這是一個簡單的方法來做到這一點! 雖然,您下次必須共享您的嘗試代碼。 請閱讀論壇規則。

 <select> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> <script> (function(){ document.currentScript.parentNode.firstElementChild.textContent = "Select here"; }()) </script> </select>

您可以使用document.querySelector()來選擇元素的第一次出現:

 document.querySelector("option").textContent = "Select here";
 <select> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </select>

您可以通過首先選擇select元素來選擇select HTML 元素的第一個子元素

const selectElement = document.querySelector("select");

因為,選項的孩子select ,那么你可以選擇特別是使用數組索引兒童和更改文本。

selectElement.children[0].textContent = "Select here"

 const selectElement = document.querySelector("select"); selectElement.children[0].textContent = "Select here"
 <select> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </select>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM