How to Get Element By Class in JavaScript?

前端 未结 11 2371
南旧
南旧 2020-11-22 01:48

I want to replace the contents within a html element so I\'m using the following function for that:

function ReplaceContentInContainer(id,content) {
   var c         


        
11条回答
  •  旧时难觅i
    2020-11-22 02:36

    I'm surprised there are no answers using Regular Expressions. This is pretty much Andrew's answer, using RegExp.test instead of String.indexOf, since it seems to perform better for multiple operations, according to jsPerf tests.
    It also seems to be supported on IE6.

    function replaceContentInContainer(matchClass, content) {
        var re = new RegExp("(?:^|\\s)" + matchClass + "(?!\\S)"),
            elems = document.getElementsByTagName('*'), i;
        for (i in elems) {
            if (re.test(elems[i].className)) {
                elems[i].innerHTML = content;
            }
        }
    }
    
    replaceContentInContainer("box", "This is the replacement text.");
    

    If you look for the same class(es) frequently, you can further improve it by storing the (precompiled) regular expressions elsewhere, and passing them directly to the function, instead of a string.

    function replaceContentInContainer(reClass, content) {
        var elems = document.getElementsByTagName('*'), i;
        for (i in elems) {
            if (reClass.test(elems[i].className)) {
                elems[i].innerHTML = content;
            }
        }
    }
    
    var reBox = /(?:^|\s)box(?!\S)/;
    replaceContentInContainer(reBox, "This is the replacement text.");
    

提交回复
热议问题