简体   繁体   中英

get element by class, target all elements on page with class name

i am trying to show different project stages within a pipeline. When the user hovers on each stage of the pipeline, the border color on the projects within that stage changes to highlight them. Pretty simple.

Well i cannot seem to target all of the items in the class on that page, it is only letting me target one using [0]. But i need it to get all the divs within that class, not just 1. Seems like an easy fix but i cannot seem to find anything regarding this.

    <script>
function scanSHOW() {

    document.getElementsByClassName('scan-item')[0].style.border="2px #FF0000 solid";}

function scanHIDE() {   

document.getElementsByClassName('scan-item')[0].style.border="2px #666666 solid";}

    </script>


<style>.scan-item {border: 2px #666666 solid;}</style>

HTML:

<img id="pipes" src="pipeline.png" usemap="#pipeline" width="483" height="221">

<map name="pipeline">
  <area shape="rect" coords="1,69,66,221" href="#" onMouseOver="scanSHOW();" onMouseOut="scanHIDE();" alt="Scan" title="Scan">

</map>

<br/>

<div  class="scan-item block"></div> <div  class="scan-item block"></div> <div  class="scan-item block"></div> <div  class="scan-item block"></div>

This is precisely what loops are for. A simple for loop that cycles through each element in turn would do the trick. Something like:

var elements = document.getElementsByClassName('scan-item');
for (var i = 0; i < elements.length; i++) {
    elements[i].style.border="2px #FF0000 solid";
}

The easiest I find is to set a click listener on the whole body and then listen for clicks with a certain class. That way you can traverse the dom for the clicked object and then do whatever you need.

function clickHandler(e){

e = e || window.event;
const target = e.target || e.srcElement;

    if (target.className.match(/CLASS NAME HERE/)) {
        //do something with the target (traverse up or down - change the element or whatever have you)
        console.log(e.target)
    }

}

if (document.body.addEventListener){
document.body.addEventListener('click', clickHandler, false);
}

Ps! If you do the for loop then I usually run into problems later this above is the most reliable (at least for me).

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