I've learned how to add a class name to a div within a specific div class here
If a specific class name is on the same page as shown below
Is there a way to add it to a div class within another div class?

As an image, only when the class name "box1" div is in the same page
I want to add box2_del to the class name "box2_in".
(Added for htmlPage1, not added for htmlPage2)


var box = document.getElementsByClassName ('box1');
var boxin = box.querySelector (". box2_in");
boxin.classList.add ('box2_del');
  • Answer # 1

    getElementsByClassName is supposed to return multiple elements, so it returns something like an array called HTMLCollection.

    var box = document.getElementsByClassName ('box1');
    var boxin = box [0] .querySelector (". box2_in");
    // ↑ When processing only the first element
    boxin.classList.add ('box2_del');

    [Document.getElementsByClassName ()-Web API | MDN]

    [Difference between the return value of getElementsByClassName and getElementById-Qiita]

Related articles