简体   繁体   English

如何将CSS应用于没有类的div?

[英]How to apply css to div which has no class?

I am creating some design part in HTML. 我正在HTML中创建一些设计部分。 I have two div. 我有两个分区。 Both div element are generating through java script. 两个div元素都是通过Java脚本生成的。 First div has a class and second div has no any class or id. 第一div有一个类,第二div没有任何类或ID。 I want to apply style to second div. 我想将样式应用于第二个div。

<div class="class_name"></div>
<div style="display:block;"></div>

After applying style the second div style will be style="display:none;" 应用样式后,第二个div样式将为style =“ display:none;”。

Please suggest. 请提出建议。

You can have CSS only solution for this, there is no need to have a javscript for this you can try adjacent siblings selectors of CSS: 您可以为此使用仅限CSS的解决方案,而无需使用javscript,可以尝试使用CSS的相邻兄弟选择器

To target very next div you need this: 要定位到下一个div,您需要这样做:

.FirstClassName + div{
  /*your style goes here */
}

To target all divs in a parent after a given class name: 要在给定的类名之后定位父级中的所有div:

.FirstClassName ~ div{
  /*your style goes here */
}

Demo 演示版

You can use :not selector for the second div : 您可以在第二个div使用:not选择器:

div:not([class="classname_of_the_first_div_here"]){}

or even simpler : 甚至更简单:

div:not(.classname_of_the_first_div_here)

假设在创建两个div元素之前没有其他div

document.getElementsByTagName("div")[1].style.color = "blue";

在第二个div中使用样式属性

<div id="div1" style="display:block;"></div>

if it has only two div's then use the last-child property. 如果只有两个div,则使用last-child属性。

yourparent div:last-child
{
your style
}

You basically have three options (maybe more, but then we need some code). 您基本上有三个选择(也许更多,但是我们需要一些代码)。

First one, use the element selector. 第一个,使用元素选择器。 but that means you're styling all elements of the same type on the page 但这意味着您要在页面上样式相同类型的所有元素

div { background: red; }

Second option, style all divs that have no class attribute: 第二个选择,设置所有没有class属性的div的样式:

div:not([class]) { background: green; }

and last but not least, style a div that is a child of another element. 最后但并非最不重要的一点是,将div样式设置为另一个元素的子元素。 If your document structure is build up properly this is most probably the way to go. 如果您的文档结构正确构建,则很可能是这样。

div.parent > div { background: blue; }

Checkout the Fiddle here 这里签出小提琴

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

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