繁体   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