Changing background color of all elements with the same class

后端 未结 3 1346
天命终不由人
天命终不由人 2020-12-11 16:17

I have a link and a table row that have matching classes. When the link is clicked, I would like to change the background color of the row with the same class. For each ca

相关标签:
3条回答
  • 2020-12-11 16:40

    You have several errors. You mixed classes with ids and also the class property is actually className

    <script type="text/javascript">
    
    function check(x) {
        elements = document.getElementsByClassName(x);
        for (var i = 0; i < elements.length; i++) {
            elements[i].style.backgroundColor="blue";
        }
    }
    
    </script>
    
    <a href="#" class="first" onclick="check(this.className)">change first row</a>
    <a href="#" class="second" onclick="check(this.className)">change second</a>
    <!--        FIX ( id -> class )                FIX ( class -> className ) -->
    <table>
    <tr class="first">
    <td>test1</td>
    </tr>
    
    
    <tr class="second">
    <!--FIX ( id -> class ) -->
    <td>test2</td>
    </tr>
    </table>
    

    Check this jsfiddle

    0 讨论(0)
  • 2020-12-11 17:02

    You can also do it easily without jQuery with querySelectorAll():

    <script type="text/javascript">
    
    function check(selector)
    {
        var elements = document.querySelectorAll(selector);
        for (var i = 0; i < elements.length; i++) {
            elements[i].style.backgroundColor = "blue";
        }
    }
    </script>
    
    <a href="#" class="first" onclick="check('.' + this.className)">change first row</a>
    <a href="#" id="second" onclick="check('#' + this.id)">change second</a>
    
    <table>
    <tr class="first">
        <td>test1</td>
    </tr>
    
    
    <tr id="second">
        <td>test2</td>
    </tr>
    
    0 讨论(0)
  • 2020-12-11 17:02

    jQuery simplifies it:

    $(".button").click(function(){
     var class = $(this).attr("data-class");
     var color = $(this).attr("data-color");
     $("."+class).css("background-color",color);
    });
    

    .button is the class to apply to the button, add data-class for the class you would like to change the background color of, and data-color is the color you would like to change it to.

    0 讨论(0)
提交回复
热议问题