-2

我有什么办法可以定位第三个 div 是这个列表并为其应用一个新的 CSS 类?

如果可能,使用 CSS、JS 或 jQuery。(或任何其他人能想到的)

<div class="item"><p>TEST TEST</p></div>
<div class="item"><p>TEST TEST</p></div>
<div class="item"><p>TEST TEST</p></div>
<div class="item"><p>TEST TEST</p></div>
<div class="item"><p>TEST TEST</p></div>
<div class="item"><p>TEST TEST</p></div>
4

8 回答 8

4

没有 CSS 类这样的东西。CSS 有选择器。一种类型的选择器是类选择器。HTML 有类。

您可以组合任意数量的选择器。听起来您想要nth-child 伪类选择器

.item:nth-child(3) { }
于 2013-09-19T11:01:34.623 回答
4

没有“CSS 类”之类的东西,更不用说它的实例了。您想要的是定位div属于某个类的元素中的第三个(在 HTML 标记中分配给它)。

答案是这取决于周围的环境。如果不知道此div元素序列如何嵌套在其他元素中以及哪些元素(尤其是div可能出现在它之前的元素),就无法定位所需的元素。

例如,如果我们假设这些元素构成了类似 元素的内容<div class=foo>...</div>,那么它很简单:

.foo > :nth-child(3) { /* CSS declarations here */ }

但是:nth-child(),某些旧版本的 IE 不支持伪类。

于 2013-09-19T11:05:14.327 回答
4

纯 JavaScript 解决方案

您可以使用getElementsByClassName

// Gets the third element with the class "item"
element = document.getElementsByClassName("item")[2];
// Assigns a new class to it
element.setAttribute("class", "newclass");
于 2013-09-19T11:07:14.797 回答
3

如果你想要一个 CSS 解决方案,你可以这样做

div.item:nth-of-type(3) {
   /* Target 3rd div */
}

这不会添加一个类,但会针对第三个div

演示


我不知道什么是downvotes,但还要确保将这些元素绑定在一个包装器元素div中,例如拥有类,wrapper这样选择器将是

div.wrapper > div.item:nth-of-type(3) {
   /* Styles here */
}
于 2013-09-19T11:00:48.050 回答
3

使用 jQuery:

$("div.item:eq(2)").addClass("test");

演示

于 2013-09-19T11:02:38.880 回答
3

使用普通的 JS:

var items = document.getElementsByClassName("item");
myItem = items[2]; // as the first element is 0, third element is position 2 in the array;
myItem.setAttribute('class', 'myClass');

更短的方法是:

document.getElementsByClassName('item')[2].setAttribute('class', 'myClass');

您必须小心使用此方法和其他方法,因为如果页面上还有其他带有“item”类的东西,它也会计算在内,您能做的最好的是将所有这些 div 包装在父 div 中,给出父 div 一个 ID 或其他东西,并以父 div 为目标。

于 2013-09-19T11:11:37.783 回答
2

使用JQuery查找带有css 选择器的类“项目”,请求 3 个并添加类:

$('.item:nth-of-type(3)').addClass('new-class');
于 2013-09-19T11:07:07.683 回答
1

对于像这样的标记-

 <div id="div1" class="someclass">
        <img ... id="image1" name="image1" />
    </div>

您可以在 javascript 中执行此操作-

var d = document.getElementById("div1");
d.className = d.className + " otherclass";

并且可以在 jQuery 中使用 addClass 方法。

于 2013-09-19T11:26:40.260 回答