首页 > 解决方案 > 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;
}

标签: javascript

解决方案


为了达到您的要求,首先替换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">


推荐阅读