Select div using wildcard ID

前端 未结 9 1775
旧时难觅i
旧时难觅i 2020-11-29 11:30

How to select a div using it\'s ID but with a widcard?

If the DIV\'s ID is statusMessage_1098, I would like to select it in some way like document

9条回答
  •  野性不改
    2020-11-29 11:53

    If you don't want to use jQuery then there is another easier way to do this:

    Assign a class - for an example name it "message", and use the following:

    function getElementsByClass(searchClass,node,tag) {
        var classElements = new Array();
        if ( node == null )
            node = document;
        if ( tag == null )
            tag = '*';
        var els = node.getElementsByTagName(tag);
        var elsLen = els.length;
        var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
        for (i = 0, j = 0; i < elsLen; i++) {
            if ( pattern.test(els[i].className) ) {
                classElements[j] = els[i];
                j++;
            }
        }
        return classElements;
    }
    

    Here how you call it:

    var messages = getElementsByClass("message");
    
    for(var index=0; index < messages.length; index++) {
     // prompt the content of the div
     //alert(message[index].innerText);
    }
    

提交回复
热议问题