简体   繁体   中英

Html selector returns an html collection and I don't know how to get to the element I need to make changes on

I have 2 divs: 1 on the left half of the page (A), one on the right (B). When hovering over a certain element of the right section, I want something to be displayed over the left one.

I did this using the following approach:

 <div className="A">
             <div className="hidden-div1">DIV 1</div>   
             <div className="hidden-div2">DIV 2</div>   
             <div className="hidden-div3">DIV 3</div>   
</div>
<div className="B"> 
            <div className="base-div1">
                  <h2 onMouseOver={this.mouseOver} onMouseOut={this.mouseOut}>Project 1</h2>
            </div>
</div>

mouseOver(e){
        const hiddenDiv1 = document.querySelector(".hidden-div1");
        hiddenDiv1.style.display = "block";    
} 

mouseOut(e){
        const hiddenDiv1 = document.querySelector(".hidden-div1");
        hiddenDiv1.style.display = "none";      
}

Problem is, considering I have 3 different hidden-divs and 3 different base-divs, I wanted to make 2 universal mouseOver and mouseOut functions for all of them. The way I tried it, is this:

mouseOver(e){
      let hiddenDivName = "hidden-div" + e.target.className.slice(-1);
      let hiddenDivSelector = document.getElementsByClassName(hiddenDivName);
      hiddenDivSelector.style.display = "block";
}

but it returns "Cannot set property 'display' of undefined". I tried console logging hiddenDivSelector and it shows an HTML collection and I don't know how to get my element. I've tried reading about it and visiting other questions but I couldn't apply anything to my situation

Event target returns a reference to DOM element. On DOM elements we can use getAttribute method and replace all non-digit characters by ''; result may be used to search DOM and iterate over returned array;

mouseOver(e){
      let hiddenDivName = "hidden-div" + e.target.getAttribute('class').replace(/\D/g, '');
      let hiddenDivSelector = document.getElementsByClassName(hiddenDivName);
      Array.from( hiddenDivSelector ).forEach(el => el.style.display ) = "block";
}

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