Reputation: 592
Any way to remove "li" directly without javascript just with onclick?
$go .="<li id=\"go_$id\"><a ondblclick=\"g('$id'); return false;\">$title</a>
<a onclick=\"go('$id', 'g')\">(x)</a>
</li>\n";
I need it to be removed by clicking on (x), so together with my other function (onclick function in the code) to combine the remove so that that "li" will disappear onclick.
Upvotes: 2
Views: 18165
Reputation: 439
function remove_item(selected_item) {
selected_item.parentNode.removeChild(selected_item);
}
li {
background: #ffe5e5;
padding: 20px;
margin: 15px;
list-style-type: decimal;
}
<ul id="list">
<li class="one" onclick="remove_item(this)">React</li>
<li class="one" onclick="remove_item(this)">Node.js</li>
<li class="one" onclick="remove_item(this)">Dart</li>
</ul>
Upvotes: 1
Reputation: 185933
If you chose to separate content from behavior (HTML from JavaScript), then this would work just fine (using jQuery):
$("li").click(function() { $(this).remove(); });
Edit:
$("li a").click(function() { $(this).closest("li").remove(); });
However, I recommend a more specific selector - like .closeButton
Upvotes: 2
Reputation: 1108722
Use Node.parentNode
to obtain the parent node and use Node.removeChild()
to remove a child node. Here's the self-explanatory version of the code:
<li><a href="#" onclick="var li = this.parentNode; var ul = li.parentNode; ul.removeChild(li);">remove</a></li>
Here's a more short version:
<li><a href="#" onclick="parentNode.parentNode.removeChild(parentNode)">remove</a></li>
Here's how to use it in combination with a JS function:
<li><a href="#" onclick="remove(this)">remove</a></li>
with
function remove(link) {
link.parentNode.parentNode.removeChild(link.parentNode);
}
Upvotes: 12