Stebs
Stebs

Reputation: 11

Can someone please explain my function deleteButton(this)?

Here is the link to my codepen to see all my code: http://codepen.io/stevengangano/full/LGvRdq/

My question has to do with my deleteButton function. I have trouble grasping this concept.

I created a function for the delete button called deleteButton(item). I just want to know what does "item" and "parentNode" represent in the variable remove? Which one is the <ul> and which one is the <li>?

An explanation would be appreciated. Thanks!

Upvotes: 1

Views: 45

Answers (2)

traktor
traktor

Reputation: 19376

function deleteButton(item) {
    var remove = item.parentNode;
    remove.parentNode.removeChild(remove);
}

in your code (posted offsite) is long for

function deleteButton(item) {
    item.parentNode.parentNode.removeChild(item.parentNode); 
}

which removes the parent node of the clicked item from its grandparent node's list of children. The parent node of the delete button is listItem in code, which means an LI item will be deleted.

Elsewhere in code posted offsite (bad practice™) the delete function is defined as

removeButton.setAttribute('onclick', 'deleteButton(this);');

which is seriously really very, interesting. It suggests that setting an onclick attribute with text, after HTML parsing has been completed, causes the text to be parsed as source for a javascript function which becomes the attribute value. Okay, so a setter can do this - but onEvent setters doing this is news to me. And testing indicates it being true.

So an answer is that setting the onclick attribute of a node with text compiles the text to a function object, attaches the function object as the onclick attribute value, which when called by clicking supplies the node being clicked on as the this object for the onclick handler. If the function called removes the parent node of the clicked object, in this case an LI element gets removed.

Upvotes: 0

Rayon
Rayon

Reputation: 36609

deleteButton(item) is attached to the removeButton. this represents the current node which is button itself.

item.parentNode will be nothing but parent of the button which is li element. remove variable holds this li element.

Again remove.parentNode will return parent node of the li element which is ul element.

paretNode.removeChild removes a child node from the DOM

So in this case, UL_ELEMENT.removeChild(LI_ELEMENT);

Upvotes: 2

Related Questions