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

126
Visualizações
jquery create and return DOM element on click

I have button that creates a div on click. I want to return this created div when I click a button. But the following code actually returns this button.

 var create = $('#create').on('click', function(e){

    var content = $('<div class="foo"/>')
     
    return content

})

var test = create.trigger('click')

 console.log(test)

Result is:

init [div#create, context: document, selector: '#create']

Is this not possible to do this this way or am I missing something?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You're calling a variable ("create") which stores the event listener on the button. This is what it looks like:

var test = $('#create').on('click', function(e){

    var content = $('<div class="foo"/>')
     
    return content

}).trigger('click')

console.log(test)

This is the solution:

jQuery
var create = function() {
  return $('<div class="foo"/>');
};
var createEl = $('#create');
createEl.on('click', function() {
  console.log(create());
  // <div class="foo"></div>
});
createEl.trigger("click");
JavaScript
var create = function() {
  var el = document.createElement('div');
  el.className = "foo";
  // Add other attributes if you'd like
  return el;
};
var createEl = document.querySelector('#create');
createEl.addEventListener("click", function() {
  console.log(create());
  // <div class="foo"></div>
});
createEl.click();

(jQuery) Live example

var create = function() {
  return $('<div class="foo"/>');
};
var createEl = $('#create');
createEl.on('click', function() {
  console.log(create());
  // <div class="foo"></div>
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<button id="create">Create</button>

(JavaScript) Live example

var create = function() {
  var el = document.createElement('div');
  el.className = "foo";
  // Add other attributes if you'd like
  return el;
};
var createEl = document.querySelector('#create');
createEl.addEventListener("click", function() {
  console.log(create());
  // <div class="foo"></div>
});
createEl.trigger("click");

var create = function() {
  var el = document.createElement('div');
  el.className = "foo";
  // Add other attributes if you'd like
  return el;
};
var createEl = document.querySelector('#create');
createEl.addEventListener("click", function() {
  console.log(create());
  // <div class="foo"></div>
});
<button id="create">Create</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

No, it is not possible. You can add a function which will be executed in your event handler to do something with the object you create in the listener:

var create = $('#create').on('click', function(e){

    var content = $('<div class="foo"/>')
     
    doSomething(content)

})

create.trigger('click')

function doSomething(test) {
    console.log(test)
}

There is no other way and it is because the handler function assigned with .on() method is called when the browser triggers an event (or you use .trigger() method) and the return statement is used only to force calling event.stopPropagation() and event.preventDefault() methods (you have to return false in the handler or just assign false instead of a function as an event handler - check the documentation, section The event handler and its environment) and not to return any value when you trigger an event manually.

You can also use an external variable to store the data "generated" in your event handler:

const divs = []

var create = $('#create').on('click', function(e){

    var content = $('<div class="foo"/>')
    
    divs.push(content)

    doSomething()

})

create.trigger('click')

function doSomething() {
    console.dir(divs)
}
about 4 years ago · Juan Pablo Isaza 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