Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
HTML + Javascript: can't get all instances from two elements at once?

I want to add a CSS styling class to all instances of a selective set of elements: for example, all p elements as well as all h4 elements.

I define two JS variables which get all elements of the aforementioned tags, and insert them into an array, so that I can make a function which, in theory, should apply the selected class to all instances of the selected elements/tags.

However, when I run the code, it seems that the function assigns the class only to the first item of the array.

Code and test

<html>
  <head>
    <meta charset="utf-8">
    <title>JS Bin</title>
    <style>
      .italic { font-style: italic; }
    </style>
  </head>
    <body>
      <h4>Text goes in here</h4>
      <p>Text goes in here</p>

      <script>
        function styleTxt() {
          let h4Elems = document.getElementsByTagName("H4");
          let pElems = document.getElementsByTagName("P");
          const elemArray = [pElems, h4Elems];

          for (eachElem in elemArray) {
            let elemInsts = elemArray[eachElem];
            for (eachInst in elemInsts) {
              let givenInst = elemInsts[eachInst];
              givenInst.classList.add("italic");
            }
          }
        }
        styleTxt();
      </script>

    </body>
</html>

If I invert the order of the element tags inside the array, then the h4 element will get the .italic class but the p element will not.

Perhaps it is not possible to use the "document" directive twice? Is there an alternative method to automatically add the same class to a set of multiple (but not all) html tags?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You are looping through each property of the HTMLCollection, including properties like length, causing givenInst to be a number. Since it has no classList property, calling add on undefined creates an error and terminates the loop.

To solve this, you can use isNaN to check whether the property is a number or not:

.italic {
  font-style: italics;
}
<html>

<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    .italic {
      font-style: italic;
    }
  </style>
</head>

<body>
  <h4>Text goes in here</h4>
  <p>Text goes in here</p>

  <script>
    function styleTxt() {
      let h4Elems = document.getElementsByTagName("H4");
      let pElems = document.getElementsByTagName("P");
      const elemArray = [pElems, h4Elems];

      for (eachElem in elemArray) {
        let elemInsts = elemArray[eachElem];
        for (eachInst in elemInsts) {
          if (!isNaN(eachInst)) {
            let givenInst = elemInsts[eachInst];
            givenInst.classList.add("italic");
          }
        }
      }
    }
    styleTxt();
  </script>

</body>

</html>

However, a better way is to use a for...of loop instead:

.italic {
  font-style: italics;
}
<html>

<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    .italic {
      font-style: italic;
    }
  </style>
</head>

<body>
  <h4>Text goes in here</h4>
  <p>Text goes in here</p>

  <script>
    function styleTxt() {
      let h4Elems = document.getElementsByTagName("H4");
      let pElems = document.getElementsByTagName("P");
      const elemArray = [pElems, h4Elems];

      for (eachElem of elemArray) {
        for (eachInst of eachElem) {
          eachInst.classList.add("italic");
        }
      }
    }
    styleTxt();
  </script>

</body>

</html>

about 4 years ago · Juan Pablo Isaza Denunciar

0

You might want to prefer the for...of loop for this and make use of the spread operator. It will produce a much nicer code output:

function styleTxt() {
    const h4Elems = document.getElementsByTagName("H4");
    const pElems = document.getElementsByTagName("P");
    const elemArray = [...pElems, ...h4Elems];
    for (const eachElem of elemArray) {
        eachElem.classList.add("italic");
    }
}

Of course, you can always pick both types of elements in one go with the querySelectorAll method:

const all = document.querySelectorAll("h4, p");

// Using the for...of loop:
for ( const el of all ){
  el.classList.add("italic");
}

// Using the `forEach` method:
all.forEach( el => el.classList.add("italic") )
about 4 years ago · Juan Pablo Isaza Denunciar

0

Use Document.querySelectorAll() to get both types of elements. Iterate the NodeList with NodeList.forEach(), and add the class to each element.

function styleTxt() {
  document.querySelectorAll('h4, p')
    .forEach(el => el.classList.add('italic'));
}

styleTxt();
.italic {
  font-style: italic;
}
<h4>Text goes in here</h4>
<p>Text goes in here</p>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda