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

85
Vistas
Jquery cannot find newly added elements

The Context

To make the explanation of my issue easier, I have created a small example:

Let's say we have this simple website (index.html):

<!DOCTYPE html>
<html lang="en">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <body>
        <script id="navigation" src="nav.js"></script>
        <p>Amazing website content</p>
        <script src="something.js"></script>
    </body>
</html>

Let's say the nav.js script imports our navigation bar from a nav.html into our index.html, so the script would look something like this:

fetch('nav.html')
    .then(res => res.text())
    .then(text => {
        let oldE = document.querySelector("script#navigation");
        let newE = document.createElement("div");
        newE.innerHTML = text;
        oldE.parentNode.replaceChild(newE,oldE);
    })

and for simplicity sake our "navigation bar" (nav.html) looks like this:

<ul class="class-nav">
  <li><a href="#">Home</a></li>
  <li><a href="#">News</a></li>
  <li><a href="#">Contact</a></li>
  <li><a href="#">About</a></li>
</ul>

Finally, we have something.js which is a javascript that uses jQuery to do some stuff, for now, we just want to be able to print out elements with the class name class-nav:

jQuery(document).ready(function($) {
    "use strict";
    var magic = function() {
        $('.class-nav').each(function() {
            console.log(this);
        });
    };
    magic();
});

The Issue

If I hardcoded my navigation bar (nav.html) to the webpage (index.html), the magic() function in something.js (that uses jQuery) works and is able to print out the navigation bar class-nav.

However, if we have it in the current setup, where we have our navigation bar added to the webpage from a separate nav.html file, the magic() function isn't able to find class-nav.

Why? And how can I modify something.js to be able to retrieve class-nav using jQuery?

about 4 years ago · Juan Pablo Isaza
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