Search code examples
jqueryhtmlclickparents

Remove an element from html()?


How can I remove certain element inside html()?

For instance, I have this html links,

<ul>
    <li><a href="#" class="string-comment">Comment</a></li>
    <li><a href="#" class="string-delete-needle">Delete</a></li>
    <li><a href="#" class="string-publish-needle">Publish</a></li>
</ul>

When you click on the class of string-publish-needle, I will store the html in a variable,

var html_parents = object_parents.html();

<li><a href="#" class="string-comment">Comment</a></li>
<li><a href="#" class="string-delete-needle">Delete</a></li>
<li><a href="#" class="string-publish-needle">Publish</a></li>

and I want to remove this one which is the parent of string-publish-needle,

<li><a href="#" class="string-publish-needle">Publish</a></li>

so I can have a new html content below only,

<li><a href="#" class="string-comment">Comment</a></li>
<li><a href="#" class="string-delete-needle">Delete</a></li>

My code but does not work of course!

$('.string-publish-needle').click(function(e){

    var object = $(this);
    var object_path = object.attr('href');
    var object_parent = object.parent('li');
    var object_parents = object.parents('ul');
    var html_parents = object_parents.html();
    var html_remain = object_parents.html().remove(object_parent);

    alert(html_remain);

});

Solution

  • $('.string-publish-needle').click(function(e){
    
        var object = $(this);
        var object_path = object.attr('href');
        var object_parent = object.parent('li');
        var object_parents = object.parents('ul');
        var html_parents = object_parents.html();
        object_parent.remove();
        var html_remain = object_parents.html();
    
        alert(html_remain);
    
    });