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.
The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.
“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.
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>
You're basically doing this
$("#newButton").click(function() {
new_entry;
});
function new_entry() {
this.parent();
}
but inside the callback for the event handler, this
is native JS DOM element, not a jQuery object, so it has no jQuery methods, you have to wrap it first, as in
$("#newButton").click(new_entry);
function new_entry() {
$(this).parent();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With