简体   繁体   English

JavaScript:为div选择一个元素并更新样式

[英]JavaScript: Select an element to a div and update styling

I need to add styling to a DIV element using JavaScript. 我需要使用JavaScript向DIV元素添加样式。 I have the following DIV in my document: 我的文档中有以下DIV:

<div class="RnEpo Yx5HN   " role="presentation">

The script that I have tried is: 我尝试过的脚本是:

WebElement = document.querySelectorAll("div[class='RnEpo Yx5HN ']");
WebElement.style='height: 10000px;'
WebElement.setAttribute("height = 1000px;");

I want to achieve the same styling as this CSS: 我想要实现与此CSS相同的样式:

.RnEpo Yx5HN   
{
    height: 100000px;
}

To achieve what you require, first replace querySelectorAll() with querySelector() seeing that your only need to select the first matching element . 为了实现您所需要的,先更换querySelectorAll()querySelector()看到您只需要选择第一个匹配的元素

Consider also revising your selector from div[class='RnEpo Yx5HN '] to a more robust selector in the form of div.RnEpo.Yx5HN which is to say: 还可以考虑将选择器从div[class='RnEpo Yx5HN ']为更强大的选择器,形式为div.RnEpo.Yx5HN ,即:

Select div elements that have classes any ordering of class RnEpo and Yx5HN 选择具有类RnEpo和Yx5HN的任何顺序的类的div元素

Lastly, revise the way that you're applying the inline style so that the height attribute is directly specified on the WebElement style object. 最后,修改应用内联样式的方式,以便在WebElement style对象上直接指定height属性。

These changes make the call to setAttribute() redundant. 这些更改使对setAttribute()的调用变得多余。 Note also that; 另请注意; setAttribute() takes two arguments , and the DIV element does not have a native height attribute. setAttribute() 具有两个参数 ,并且DIV元素没有本机的height属性。

Here's a working snippet showing this in action: 这是一个工作中的片段,显示了此操作:

 /* 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"> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM