Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda