Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace jQuery function with Javascript

I need to replace this jQuery function with pure javascript.

$('#myTable span.hide').click(function () {
    $(this).closest("tr").remove();
    return false;
});

I tried to replace it with this but it doesn't work in IE.

function rem(id) {
    id.parentNode.parentNode.innerHTML = "<td></td>";
}  

Here's how the table looks:

<tbody id="thebody">
<tr>
    <td>
       <span onclick="rem(this);" class="hide"></span>
    </td>
    //More td's here
</tr>
</tbody>
like image 490
Niklas Avatar asked May 06 '26 11:05

Niklas


2 Answers

function rem(id) { // id may be ambiguous here, because it's the element, not an ID
    var elem = id; // current elem

    while(elem.nodeName !== "TR") { // move up to tr as long as it isn't tr yet
        elem = elem.parentNode; // if not tr yet, set elem to parent node
    }

    elem.parentNode.removeChild(elem); // remove tr from parent node
}

Note that your HTML should include a <table> - a raw <tbody> is invalid.

like image 144
pimvdb Avatar answered May 08 '26 02:05

pimvdb


To remove the <span> element itself, do this:

function rem(el) {
    el.parentNode.removeChild(el);
}

If you want to remove the closest <tr>, then you need something like:

function rem(el) {
    while(el.nodeName != "TR") {
        el = el.parentNode;
    }
    el.parentNode.removeChild(el);
}
like image 26
Jon Avatar answered May 08 '26 02:05

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!