Dima Poliuliuk Dima Poliuliuk - 2 months ago 4
Javascript Question

select the third element in every parent element

I need help. How do I select the

<p>
elements in every
<div>
on the page (for adding some class) beginning from the third
<p>
element?

I've tried to select like -
$('div p').slice(1).addClass('hidden');

but in result only one
<p>
element remains on the page

Answer

You could easily do this without javascript....

.thirds p:nth-child(3n) { background: red; color: #fff; }
.threeplus p:nth-child(n+3) { background: green; color: #fff; }


div { 
  margin: 20px 0; 
  background: #eee; 
  border: 1px solid #ddd; 
  padding: 20px; 
  width: 100px;
  display: inline-block;}
p { margin: 0 0 2px; padding:0; }
<div class="thirds">
  <p>One</p>
  <p>Two</p>
  <p>three</p>
  <p>Four</p>
  <p>Five</p>
  <p>Six</p>
  <p>Seven</p>
  <p>Eight</p>
  </div>

<div class="threeplus">
  <p>One</p>
  <p>Two</p>
  <p>three</p>
  <p>Four</p>
  <p>Five</p>
  <p>Six</p>
  <p>Seven</p>
  <p>Eight</p>
  </div>

To hide 3rd and following paragraph in any div, just generalize the CSS:

div p:nth-child(n+3) {  display: none; }


div { 
  margin: 20px 0; 
  background: #eee; 
  border: 1px solid #ddd; 
  padding: 20px; 
  width: 100px;
  display: inline-block;}
p { margin: 0 0 2px; padding:0; }
<div class="thirds">
  <p>One</p>
  <p>Two</p>
  <p>three</p>
  <p>Four</p>
  <p>Five</p>
  <p>Six</p>
  <p>Seven</p>
  <p>Eight</p>
  </div>

<div class="threeplus">
  <p>One</p>
  <p>Two</p>
  <p>three</p>
  <p>Four</p>
  <p>Five</p>
  <p>Six</p>
  <p>Seven</p>
  <p>Eight</p>
  </div>

<div class="thirds">
  <p>One</p>
  <p>Two</p>
  <p>three</p>
  <p>Four</p>
  <p>Five</p>
  <p>Six</p>
  <p>Seven</p>
  <p>Eight</p>
  </div>

<div class="threeplus">
  <p>One</p>
  <p>Two</p>
  <p>three</p>
  <p>Four</p>
  <p>Five</p>
  <p>Six</p>
  <p>Seven</p>
  <p>Eight</p>
  </div>

<div class="thirds">
  <p>One</p>
  <p>Two</p>
  <p>three</p>
  <p>Four</p>
  <p>Five</p>
  <p>Six</p>
  <p>Seven</p>
  <p>Eight</p>
  </div>

<div class="anotherClass">
  <p>One</p>
  <p>Two</p>
  <p>three</p>
  <p>Four</p>
  <p>Five</p>
  <p>Six</p>
  <p>Seven</p>
  <p>Eight</p>
  </div>

<div class="anotherRandomClass" id="andanID">
  <p>One</p>
  <p>Two</p>
  <p>three</p>
  <p>Four</p>
  <p>Five</p>
  <p>Six</p>
  <p>Seven</p>
  <p>Eight</p>
  </div>

<div class="moreClass">
  <p>One</p>
  <p>Two</p>
  <p>three</p>
  <p>Four</p>
  <p>Five</p>
  <p>Six</p>
  <p>Seven</p>
  <p>Eight</p>
  </div>

Comments