javascript - JavaScript:选择一个元素到一个 div 并更新样式
问题描述
我需要使用 JavaScript 为 DIV 元素添加样式。我的文档中有以下 DIV:
<div class="RnEpo Yx5HN " role="presentation">
我尝试过的脚本是:
WebElement = document.querySelectorAll("div[class='RnEpo Yx5HN ']");
WebElement.style='height: 10000px;'
WebElement.setAttribute("height = 1000px;");
我想实现与这个 CSS 相同的样式:
.RnEpo Yx5HN
{
height: 100000px;
}
解决方案
为了达到您的要求,首先替换querySelectorAll()
为querySelector()
您只需要选择第一个匹配元素。
还考虑将您的选择器从修改div[class='RnEpo Yx5HN ']
为更健壮的选择器,其形式为div.RnEpo.Yx5HN
:
选择具有任意顺序的类 RnEpo 和 Yx5HN 的 div 元素
最后,修改应用内联样式的方式,以便height
直接在 WebElementstyle
对象上指定属性。
这些更改使调用变得setAttribute()
多余。另请注意;setAttribute()
接受两个参数,并且 DIV 元素没有原生height
属性。
这是一个显示此操作的工作片段:
/* Use querySelector() to select first matching element and use dot notation syntax to select div with both classes */
const WebElement = document.querySelector("div.RnEpo.Yx5HN");
/* Apply inline style, avoid invalid setAttribute call */
WebElement.style.height = `10000px;'
<div class="RnEpo Yx5HN" role="presentation">
推荐阅读
- gdb - 如何根据 gdb 是否附加到正在运行的进程,在 gdb 中执行“运行”或“继续”?
- ios - UInt8 数组未转换为字节字符串
- asp.net - 邮件发送失败。在 ASP.NET 中
- robotframework - 如何连接在机器人框架中具有一些代理设置作为先决条件的会话
- python-3.x - python - 使用打字类手动执行打字约束
- mysql - 如何在nodejs中的续集模型mysql中列注释
- html - 如何在背景图像上有一个不透明层
- c - 使用 kill 和 pause libc 调用的意外行为同步
- hyperledger - 是否可以使用超级账本存储公共数据.....?
- php - 用于字符串层次结构的 PHP 排序