ParentNode alternative
Intended for http://stackoverflow.com/questions/35129687
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<ul id="blog-list" class="list-group">
<li class="blog-item list-group-item">
<a href="blog1.com">
Boats galore!
</a>
<span class="blog-description">
This is a blog about some of the best boats from Instagram.
</span>
<span class="blog-button delete-button badge">
Delete
</span>
<span class="blog-button edit-button badge">
Edit
</span>
</li>
<li class="blog-item list-group-item">
<a href="blog2.com">
Goats galore!
</a>
<span class="blog-description">
A blog about the everyday adventures of goats in South Africa.
</span>
<span class="blog-button delete-button badge">
Delete
</span>
<span class="blog-button edit-button badge">
Edit
</span>
</li>
<li class="blog-item list-group-item">
<a href="blog3.com">
Totes galore!
</a>
<span class="blog-description">
A blog about containers and bags, and the owners who love them.
</span>
<span class="blog-button delete-button badge">
Delete
</span>
<span class="blog-button edit-button badge">
Edit
</span>
</li>
</ul>
JavaScript
function deleteClickHandler(event, parent) {
// prevent the click event from firing for other elements
event.stopPropagation();
// `parent` will be specified as a part of a closure
// see `addClickHandlers`
parent.remove();
}
function editClickHandler(event, parent) {
// This function finds the ".blog-description" child of the parent
// and prompts the user to input a new description.
// The `parent` parameter is bound in a closure later
event.stopPropagation();
var description = parent.getElementsByClassName("blog-description")[0];
description.innerHTML = prompt("Enter a new description:");
}
function addClickHandlers() {
var bloglistElement = document.getElementById("blog-list");
// Get an HTMLCollection of all #blog-list child `*.blog-item` tags
var blogitems = bloglistElement.getElementsByClassName("blog-item");
blogitems.forEach(function(blogitem){
// Get the first child element of `blogitem` with class `delete-button`
// Instead of hard-coding the [0] index, you can return another
// HTMLCollection and do another forEach when adding the handler.
var deleteButton = blogitem.getElementsByClassName("delete-button")[0];
// Create a closure that will bind the value of the parent `blogitem`
// into our event handler for each different `blogitem`,
// effectively giving the button knowledge of its' intended parent.
deleteButton.onclick = function(event) {
// When the click event fires, this function is called with only
// one parameter - `event`. However, `blogitem` remembers its' value
// for each individual handler. So the value for `parent` in the
// event handler itself will contain the correct `blogitem`.
return deleteClickHandler(event,...