gandalf3 gandalf3 - 3 months ago 15
jQuery Question

Why isn't this.parent() defined as a function?

JSFiddle

I'm creating a new button element with

$('<button>Remove Entry</button>', { 'type': 'button', 'class': 'delete_button' });


However the neither the
type
or
class
attributes seem to be defined, and the console prints an error saying
this.parent()
is not a function (though I'm positive I enabled jquery)

I'm afraid I've done something simple and stupid, but I can't seem to find anything wrong.

Answer

The reason that the attributes are not set on the element, is that you are mixing different uses of the jQuery method.

To use the method in a way that it uses an object for attributes, the first parameter should be a single tag, not a HTML snippet:

$('<button>', { 'type': 'button', 'class': 'delete_button' }).text('Remove Entry');

The reason that this doesn't have a parent method is that it refers to an element, not a jQuery object. You would use $(this) to make a jQuery object from the element reference.

Also, this referers to the new entry button, not the remove entry button, as you are calling the method when you are binding the event. You should call the method when the event happens:

delete_button.click(function() {
  remove_entry($(this).parent())
});

Demo: http://jsfiddle.net/Guffa/9TcpB/1/

  var entries = 0;
  
  function new_entry() {
    entries++
    new_entry_div = $('<div>', { 'class': 'entry' }).appendTo('form');
    new_entry_div.html('<p><input type="text"></p>')

     
//     delete button
    delete_button = $('<button>', { 'type': 'button', 'class': 'delete_button' }).text('Remove Entry');
    delete_button.appendTo(new_entry_div);
      delete_button.click(function(){
          remove_entry($(this).parent());
      });
  }
  
  function remove_entry(entry) {
    entry.remove();
  }
  
  $("#newButton").click(function () {
    new_entry();
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input">
      <form>
      </form>
      <button id="newButton">New Entry</button>
    </div>