Home > Mobile >  add new class to children container in html/css with javascripth
add new class to children container in html/css with javascripth

Time:01-24

I'm a beginner in using javascript with html and css. I want to try is there a way to access child container class via parent container class. or can I add a new class("second_new") to "second" class via "first" class.

/* CSS */
.first {
  background-color: red;
}

.first_new {
  background-color: pink;
}

.second {
  background-color: blue;
}

.second_new {
  background-color: purple;
}
<!-- HTML -->
<div >
  <div >
      <h1>This is first class</h1>
      <div > <!-- I want to change this -->
          <h2>This is Second class</h2>
      </div>
  </div>
  <div >
      <h1>This is first class</h1>
      <div > <!-- I want to change this -->
          <h2>This is Second class</h2>
      </div>
  </div>
  
</div>
<!-- JAVASCRIPT -->
<script>
    var firstClass = document.getElementsByClassName("first");

    function Mousein() {
        this.classList.add("first_new");

    };
    
    function Mouseout() {
        this.classList.remove("first_new");

    };

    for (var i = 0; i < firstClass.length; i  ) {
        firstClass[i].addEventListener('mouseover', Mousein);
        firstClass[i].addEventListener('mouseout', Mouseout);

    }
</script>

CodePudding user response:

yes you can

Method 1

document.querySelector('.first .second');

Medthod 2

let parent = document.querySelector('.first');
parent.querySelector('.second');

CodePudding user response:

Yes you can access bey selector. document.querySelector('parent child') . In your case would be: const childEl = document.querySelector('.first .second');

  •  Tags:  
  • Related