如何删除重复的ID?

时间:2015-02-11 21:16:10

标签: javascript

<td id="table_line_0">
<input id="btnAdd0" type="button" value="+" onClick="newLine()">
</td>
<td id="table_line_0">
<input id="btnAdd1" type="button" value="+" onClick="newLine()">
</td>

我需要一个javascript函数来删除两个id(table_line_0)... tks !!

function removeID(id)
{

 ... I do not know what to do to find duplicate id ..

 line_table = document.getElementById(id);
 line_table.parentNode.parentNode.removeChild(line_table.parentNode);
}

我有两个'tr'具有相同的ID ...我想删除具有相同ID的'tr'..

2 个答案:

答案 0 :(得分:0)

如果我正确地提出了您的问题(在通讯中是准确的),您希望删除包含重复trtd的{​​{1}}个id。这就是你能做的:

function removeTr(id) {
    var ids = document.querySelectorAll(id), // Get a collection of cells with same ids
        len = ids.length,
        n;
    if (len < 2) {return;} // Quit, no duplicated ids
    for (n = 0; n < len; n++) { // Iterate through the collection
        if (ids[n]) { // Check, if the element exists
            ids[n].parentElement.removeChild(ids[n]); // If the wanted id is found, remove the parent
        }
    }
}

A live demo at jsFiddle

然后使用想要的removeTr('#table_line_0');作为参数调用id

答案 1 :(得分:-1)

首先,拥有重复的ID是一种愚蠢的行为。但是如果你以某种方式做过,也许加载多个具有相同IDS的ajax源。然后你可以删除这样的ID:

<强> HTML

<div id='id1'>ID1</div>
<div id='id1'>ID1</div>

JavaScript (jQuery)

do {
    $("#id1").removeAttr("id");
} while ( $("#id1").size() > 0 );

修改

JavaScript (没有jQuery)

do {
    document.getElementById("id1").removeAttribute("id");
} while (document.getElementById("id1") != null);

希望这有帮助