删除具有特定className的所有DOM元素

时间:2010-11-01 08:34:42

标签: javascript

如何删除具有以特定模式开头的特定类名或元素宽度ID的所有DOM元素。喜欢(没有任何框架!)

id="selectbox1"
id="selectbox2"
id="selectbox3"
id="selectbox4"

由于

3 个答案:

答案 0 :(得分:2)

您必须使用getElementsByTagName(*)迭代整个集合,使用正则表达式.className检查/\bYourClasName\b/属性(className可以有多个类,用空格分隔)然后还要检查元素的.id属性与另一个正则表达式:/^IDStartsWithThis/最后匹配您必须调用的任何匹配项element.parentNode.removeChild(element);

(在我上班和匆忙的路上,如果你需要更多的代码,我可以提供它,一旦我到达那里大约630 est)

编辑:这是代码:

用法:removeElemIf(idStartsWith,containsClass)。你可以传递null,只传递id(第二个参数未定义),空白(忽略空格,首先修剪两个参数)。 Case对两个参数都不敏感。

function removeElemIf(theID, theClass) { /* class => full match, id => startswith */

    checkID = !(theID === undefined || theID === null || (theID = theID.replace(/^\s*|\s*$/g, '')).length == 0);
    checkClass = !(theClass === undefined || theClass === null || (theClass = theClass.replace(/^\s*|\s*$/g, '')).length == 0);

    if (!(checkID || checkClass)) return;

    var oBody = document.getElementsByTagName('body')[0]; // only search the body
    var oElems = oBody.getElementsByTagName('*'); // get all the elements within body

    for (i = oElems.length - 1; i >= 0; i--) { // loop through backwards in case of delete

        el = oElems[i]; // set current element
        found = false;  // reset flag

        if (checkID) { /* check the ID for starting with "theID", originally used indexOf but its case sensitive*/
            re = new RegExp('^'+theID,'i'); 
            if (el.id.match(re)) found = true;
        }

        if (!found && checkClass) {   /* only test class if the id doesn't match,
                                      save the regex in instances where the
                                      class names are long or many*/
            re = new RegExp('\\b' + theClass + '\\b', 'i');
            if (el.className.match(re)) found = true;
        }

        if (found) el.parentNode.removeChild(el); /* if found, remove from parent */

    }

}

答案 1 :(得分:1)

遍历dom树并与找到的每个元素的className属性进行比较。是的,这很乏味,但这就是它的完成方式。您可以以递归方式遍历,也可以以迭代方式遍历。第一个是最容易写的,但第二个有更好的性能。

答案 2 :(得分:-1)

看到这个SO线程: jQuery matching pattern

并查看getElementsByTagName()功能