3

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>

3 Answers 3

7
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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

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

5 Comments

This will remove the td not the tr element, which is what the jQuery version does.
Your code replace the TD with blank TD, my code just clean the TD contents. Whats the difference? You want to clean the td attributes too?
I think @Shef refers to his jQuery function and not his attempt to recreate the function with pure JavaScript.
@Stefan: I referred to OP's jQuery code, not mine if that's what you want to say. Correction on my first comment: I meant "this will remove the content of td not the tr itself."
Sorry, of course I ment that you referred to Niklas(his) jQuery function :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.