[英]Find class inside ID and change attribute of element
我有這個 HTML:
<div class="myclass" id="myid">
嘗試使用以下內容在此類中搜索具有此 ID 的元素:
var getDiv = document.getElementById("myid").getElementsByClassName("myclass")[0];
getDiv.setAttribute("style", "visibility: hidden");
這將getDiv
返回為“未定義”
我將有許多具有相同類或 ID 的元素,但頁面上只有一個元素同時存在。
你試圖做的是無效的。 id 只用於一個元素,class 用於多個元素。 而你只能這樣做:
var something = document.getElementById("myId");
something.setAttribute(...);
或者
var something = document.getElementsByClassName("myClass"); //this is now array of elements
something[0].setAttribute(...); // I chose first element
我希望這有幫助。 要了解有關 id 與 class 的更多信息,請單擊此處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.