Search code examples
javascripthtmlclickes6-class

How can i select all elements using the help of this in ES6 class


I am trying to just access all child elements of a container. I created an ES6 class for this. I need class approach as per my project requirement. My target is, when i click on any child element, all the child elements needs to be selected. As an example now, i given a red border to all child elements when i click on any child element. If you see my code, following line is the main thing i need help let children = parent.querySelectorAll(".child"); now i used .child class here. But how can i use this.children here. The comple line should be like this let children = parent.querySelectorAll(this.children);. How can i achieve this. My code is as follows. If i get this, it will be very helpfull. Hopes anyone can be help me on it. Thanks in Advance!

class Selector{
constructor(parents, children) {

this.parents= document.querySelectorAll(parents);
this.children= document.querySelectorAll(children);

this.selectall=()=>{
this.children.forEach((elem)=>{
elem.addEventListener("click",(e)=>{
 let parent = e.target.parentElement;
 let children = parent.querySelectorAll(".child");
 children.forEach((elem)=>{elem.style.border="2px solid red"});
    })
  })
 }
}
}

let one = new Selector(".parent",".child");
one.selectall();
.parent {font-family:Arial, Helvetica, Sans-serif;}
<ul class="parent">
<li class="child">One</li>  
<li class="child">Two</li>  
<li class="child">Three</li>    
</ul>
    
    
<ul class="parent">
<li class="child">One</li>  
<li class="child">Two</li>  
<li class="child">Three</li>    
</ul>


Solution

  • Solution 1 (If parent has all children with child class):

    Instead of

    let children = parent.querySelectorAll(".child");
    

    Try this

    let children = Array.from(parent.children);
    

    Solution 2 (If parent has children with class other than child)

    Store the child class as well.

    class Selector {
      constructor(parents, children) {
        this.parents = document.querySelectorAll(parents);
        this.childrenClass = children;
        this.children = document.querySelectorAll(children);
    
        this.selectall = () => {
          this.children.forEach((elem) => {
            elem.addEventListener("click", (e) => {
              let parent = e.target.parentElement;
              let children = parent.querySelectorAll(this.childrenClass);
              children.forEach((elem) => {
                elem.style.border = "2px solid red";
              });
            });
          });
        };
      }
    }
    
    let one = new Selector(".parent", ".child");
    one.selectall();