javascriptremovechild

Get next element outside span


I have the following code:

<span class='myClass'>My Text</span><button class='myBtn'>OK</button>
<span class='myClass'>My Text</span><button class='myBtn'>OK</button>
<span class='myClass'>My Text</span><button class='myBtn'>OK</button>

I'm looking to click on any of myClass and remove it's contents PLUS remove button right after that. I don't want to remove others - just the one I click on.

Thanks for any help.


Solution

  • If you are using jQuery:

    $('.myClass').click(function() {
        $(this).next().remove();
        $(this).remove();
    });
    

    If plain javascript:

    var spans = document.getElementsByClassName('myClass');
    for(var i = 0; i < spans.length; i++) {
        spans[i].onclick = function() {
            this.parentNode.removeChild(this.nextSibling);
            this.parentNode.removeChild(this);
        };
    }