2

What i am trying to do here is modifying the element and adding attribute (class) using JS.

JS Script

 var x = document.querySelectorAll(".clearfix div"); x[0].setAttribute("class", "regDesign"); x[1].setAttribute("class", "regDesign"); 

HTML Default Format

<div class="clearfix"> <div> <div></div> <div></div> <div></div> <div></div> <div></div> a lot of divs here </div> <div> <div></div> <div></div> <div></div> a lot of divs here </div> </div> 

HTML Result

<div class="clearfix"> <div class="regDesign"> <div class="regDesign"></div> </div> <div> <div></div> </div> </div> 

Desired HTML Result

<div class="clearfix"> <div class="regDesign"> <div></div> </div> <div class="regDesign"> <div></div> </div> </div> 

Thank you for helping.

1
  • have you tried document.querySelectorAll(".clearfix div div"); Commented Aug 13, 2020 at 17:26

3 Answers 3

2

You can modify the selector as follows:

var x = document.querySelectorAll(".clearfix > div"); x[0].setAttribute("class", "regDesign"); x[1].setAttribute("class", "regDesign"); console.log(document.getElementsByClassName("clearfix")[0].innerHTML);
<div class="clearfix"> <div> <div></div> </div> <div> <div></div> </div> </div>

You can read more here.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you sir for helping. But what if i have a lot of div below it. I want to do it dunamically. I will be changing my question sir.
@EmelioSteveMalisa You are welcome.This is done dynamically. What output are you hoping for?
Loop thru if you have a bunch of divs in the collection
1

You can do something like this for any number of <div>
For adding classes, use classList.add() instead of setAttribute()

var x = document.querySelectorAll(".clearfix > div"); for(let i = 0; i < x.length; i++) { x[i].classList.add("regDesign"); } console.log(document.getElementsByClassName("clearfix")[0].innerHTML);
<div class="clearfix"> <div> <div></div> </div> <div> <div></div> </div> </div>

Comments

0

This will do it dynamically, even if there is more than one div in each div:

var x = document.querySelectorAll(".clearfix>div"); x[0].setAttribute("class", "regDesign"); x[1].setAttribute("class", "regDesign"); 

1 Comment

.clearfix > div, thank you sir. This does the trick. I will be looking on this and understand how this " > " works. thankssss

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.