When using jQuery append it displays the text [object Object] and does not insert the element

1

I created a div.box in the html and in it I want to insert another div that I create in the code execution, follow the abbreviation:

HTML:

<div class="box"></div>

JS:

var item = $('<div />', {class: 'item'})
var box = $('.box')

box.on('click', function (e) {
  this.append(item)
})

But instead of appearing the div.item inside div.box appears the text [object Object]. I realized that this only happens when executed in the click event, doing the form below works:

var item = $('<div />', {class: 'item'})
var box = $('.box')
box.append(item)

Does anyone have an explanation for this?

    
asked by anonymous 20.02.2017 / 14:50

2 answers

4

When using this you are using a Pure JavaScript object that does not have JQuery implementations, to correct just cast 1% on this

box.on('click', function (e) {
  $(this).append(item)
})

If you give a console.log in this and $(this) you will see that $(this) has several more properties than this native.

    
20.02.2017 / 15:03
3

You have failed to put this "inside" of jquery $(this) , in your click.

I just gave you a modified one so you can see it working.

$('document').ready(function(){
  var item = $('<div>NOVO TEXTO</div>');
  var box = $('.box');

  box.on('click', function (e) {
    $(this).append(item)
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="box">TEXTO</div>
    
20.02.2017 / 15:03