nHa*_*ins 2 javascript jquery traversal
我想创建一个脚本,它将为没有特定类的第一个子类添加一个类,每个父类都有一个特定的类.例如:
<div class="wrap">
<p class="no">1. Not this one please</p>
<div>
<p>2. not this either</p>
</div>
<p>3. Make this red!</p>
<p>4. Not this</p>
</div>
<div class="wrap">
<p class="no">5. Not this one please</p>
<p>6. Make this red also!</p>
<p>7. Not this</p>
</div>
Run Code Online (Sandbox Code Playgroud)
我的javascript如下:
$('div.wrap').find('p:not(.no):first').addClass('red');
Run Code Online (Sandbox Code Playgroud)
这将选择后代而class="no"不是第一个孩子(因此第2项,而不是上例中的第3项).我已尝试更改.find为.children,但之后它只选择页面上的第一个示例,而不是每个集合中的第一个示例(因此上面示例中只有项目2,而不是项目6).
这是一个说明上述http://cdpn.io/izGDH的codepen
你很亲密!你想添加一个指令只抓住直接后代:">"
$('div.wrap').find('> p:not(.no):first').addClass('red');
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/wnewby/HUqR9/