How to edit an HTML class, from Javascript

1

Good, I'd like you to help me, I'm doing in javascript so that a class can change color, but I do not know what I'm doing wrong I would like you to help me, this is my code:

Javascript:

 <script>
          $(document).ready(function () {

              document.getElementsByClassName("colourButton").style.color = "#FF0000";

          });
    </script>

HTML:

  <form id="form1" runat="server">
        <div>
            <table border="1">
                <tr >
                    <th>nombre</th>
                    <th>apellidos</th>
                </tr>
                <tr class="colourButton">
                    <td >piero</td>
                    <td>Flores</td>
                </tr>
            </table>

        </div>
    </form>

I get this image:

    
asked by PieroDev 21.10.2017 в 16:31
source

2 answers

1

The problem is that the method to obtain classes, obtains a collection of HTML elements, with the same class. So it's like an array, but you can not use its methods, that's why I use Array.from (), which is like transforming it to work with the array.

window.addEventListener("DOMContentLoaded",function(){
  var c = document.getElementsByClassName("misma");
  Array.from(c).forEach(e => {
    e.style.color = "red";
  });
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Ejemplo clases</title>
</head>
<body>
  <i class="misma">Soy de la misma clase</i>
  <br><br>
  <b class="misma">Yo tambieen!!</b>
  
</body>
</html>
    
answered by 21.10.2017 / 16:57
source
0

Try this, insert the jquery library, I hope it works for you.

          $(document).ready(function () {

     document.getElementsByClassName("colourButton")[0].style.color = "#FF0000";

          });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" runat="server">
        <div>
            <table border="1">
                <tr >
                    <th>nombre</th>
                    <th>apellidos</th>
                </tr>
                <tr class="colourButton">
                    <td >piero</td>
                    <td>Flores</td>
                </tr>
            </table>

        </div>
    </form>

I hope it works for you.

    
answered by 21.10.2017 в 16:52