简体   繁体   中英

only apply css style to first available class element within div using javascript

I have the following html:

<div class="comment">
  <div class="text">
     <p class="para">test</p>
     <p class="para">test2</p>
  </div>
</div>
<div class="comment">
  <div class="text">
     <p class="para">test3</p>
     <p class="para">test4</p>
     <p class="para">test5</p>
     <p class="para">test6</p>
  </div>
</div>
<div class="comment">
  <div class="text">
     <p class="para">test7</p>
     <p class="para">test8</p>
  </div>
</div>

And then at the bottom of the page is some javascript:

<script>
 var x = document.getElementsByClassName("para");
 var i;
 for(i=0;i<x.length;i++){
   x[i].style.marginTop="120px";
 }
 </script>

The javascript loops through all of the para class elements and applies a 120px margin top .

The problem is i only want the first para within each text div to have a 120px margin top.

So, the solution should have the first para element within each text div to have a margin top , which would include test,test3,test7

If you're open to using CSS, you could use .text > .para:first-child to set the margin-top . It is certainly more efficient than using Javascript.

 .text > .para:first-child { margin-top: 120px; } 
 <div class="comment"> <div class="text"> <p class="para">test</p> <p class="para">test2</p> </div> </div> <div class="comment"> <div class="text"> <p class="para">test3</p> <p class="para">test4</p> <p class="para">test5</p> <p class="para">test6</p> </div> </div> <div class="comment"> <div class="text"> <p class="para">test7</p> <p class="para">test8</p> </div> </div> 

You could also use the same selector with document.querySelectorAll to get the matching elements, and set the margin-top on them if you want.

 var elems = document.querySelectorAll('.text > .para:first-child'); elems.forEach(function(elem) { elem.style["margin-top"] = "120px"; }); 
 <div class="comment"> <div class="text"> <p class="para">test</p> <p class="para">test2</p> </div> </div> <div class="comment"> <div class="text"> <p class="para">test3</p> <p class="para">test4</p> <p class="para">test5</p> <p class="para">test6</p> </div> </div> <div class="comment"> <div class="text"> <p class="para">test7</p> <p class="para">test8</p> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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