开发者

removing all the DOM Elements with a specific className

How I can rem开发者_开发知识库ove all DOM Elements with specific classname or element width ID's that start with a specific pattern. like (without any framework!)

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

Thanks


You'd have to use getElementsByTagName(*) iterate over the entire collection, check the .className property with a regex /\bYourClasName\b/ (className can have more than one class, seperated by a space) and then also check the element's .id property with another regex: /^IDStartsWithThis/ finally on any matches you would have to call element.parentNode.removeChild(element);

(On my way to work and in a rush, if you need more code I can supply it once I get there around 630 est)

Edit: here's the code:

usage: removeElemIf(idStartsWith,containsClass). you can pass null, only the id (second param is undefined), blanks (blanks are ignored, both parameters are trimmed first). Case is insensitive for both parameters.

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 */

    }

}


Traverse through the dom tree and compare against the className property of each element found. Yes it's tedious, but that's how it's done. You can either traverse in a recursive fashion or an iterative one. The first is the easiest to write, but the second has much better performance.


see this SO thread: jQuery matching pattern

and check out getElementsByTagName() function

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜