-3

Script doesn't work. I want to make "tiposDeFrutas" visible with display attribute when I click over "nombreDeLista". I also add the CSS document.

.tiposDeFrutas {
  display: none;
}
<!DOCTYPE html>
<html>

<head>
  <title>Pruebas HTML</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel=StyleSheet href="newcss.css" type="text/css" media=screen>
  <script>
    document.onload = function() {
      document.getElementById("nombreDeLista").onclick = function() {
        document.getElementsByClassName("tiposDeFrutas").style.display = "block";
      };
    };
  </script>
</head>

<body>
  <div id="nombreDeLista">Frutas</div>
  <div class="tiposDeFrutas">Pera</div>
  <div class="tiposDeFrutas">Limón</div>
</body>

</html>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101

2 Answers2

5

document.getElementsByClassName("tiposDeFrutas") will return an array of objects, you could target the first using [0] :

document.getElementsByClassName("tiposDeFrutas")[0].style.display = "block";

If you want to show all the elements you could loop through them using for loop.

document.getElementById("nombreDeLista").addEventListener('click', showAll, false);

function showAll() {
  var tiposDeFrutas = document.getElementsByClassName("tiposDeFrutas");
  
  for (var i = 0; i < tiposDeFrutas.length; i++) {
    tiposDeFrutas[i].style.display = "block";
  }
}
.tiposDeFrutas {
  display: none;
}
<div id="nombreDeLista">Frutas</div>
<div class="tiposDeFrutas">Pera</div>
<div class="tiposDeFrutas">Limón</div>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

Final code

<!DOCTYPE html>
    <html>
        <head>
            <title>Pruebas HTML</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link rel=StyleSheet href="newcss.css" type="text/css" media=screen>
            <script>
                window.onload = function () {
                    document.getElementById("nombreDeLista").onclick = function () {
                        elementos = document.getElementsByClassName("tiposDeFrutas");
                        for (var i = 0; i < elementos.length; i++) {
                            elementos[i].style.display = "block";
                        }
                    };
                };
            </script>
        </head>
        <body>
            <div id="nombreDeLista">Frutas</div>
            <div class="tiposDeFrutas">Pera</div>
            <div class="tiposDeFrutas">Limón</div>
        </body>
    </html>