簡體   English   中英

在 ID 中查找類並更改元素的屬性

[英]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.

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