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

220
Vistas
es6 class find array object class from element

I have 2 classes parent/child. In the parent class I need a way to return/find the child class from the clicked on element.

I am getting: 'find(...).toggle is not a function'

Here in a minimal example:

class card {
  constructor(parent, element) {

    this.parent = parent;
    this.element = element;
  }

  toggle(expand) {
    //Do stuff
  }
}

class cards {
  constructor() {
    this.element = $(".cards");
    this.cards = [];


    this.element.children(".card").each((obj, el) => {
      console.log(el);
      this.cards.push(new card(this, $(el)));
    });

    $(document).click((event) => {
      var clickedOn = $(event.target);
      var $thisClosest = clickedOn.closest(".card");

      find($thisClosest).toggle();
    });
  }

  find(element) {
    this.cards.forEach((obj, el) => {
      if ($(el) == element)
        return obj; // need to return the class card
    });
  };

}

var my_a = new cards();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="cards">
  one asdf
  <div class="card">card 1 asdf</div>
  <div class="card">card 2 asdf</div>
</div>

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

You should use this.cards.find instead of this.cards.forEach as Array.forEach does not return any value.

Array.find will return first element from array that matches the condition.

find(element) {
  return this.cards.find((card) => card.element.is(element)));
};

I also used jQuery's .is() as a more robust way to compare elements.

about 4 years ago · Santiago Gelvez 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