Niklas
Niklas

Reputation: 13135

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>

Upvotes: 3

Views: 549

Answers (3)

Jon
Jon

Reputation: 437376

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);
}

Upvotes: 3

pimvdb
pimvdb

Reputation: 154828

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.

Upvotes: 7

hungryMind
hungryMind

Reputation: 6999

function rem(id) {
    id.parentNode.innerHTML = "";
} 

Upvotes: 0

Related Questions