How to Get Element By Class in JavaScript?

前端 未结 11 2346
南旧
南旧 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条回答
  •  迷失自我
    2020-11-22 02:13

    This code should work in all browsers.

    function replaceContentInContainer(matchClass, content) {
        var elems = document.getElementsByTagName('*'), i;
        for (i in elems) {
            if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')
                    > -1) {
                elems[i].innerHTML = content;
            }
        }
    }
    

    The way it works is by looping through all of the elements in the document, and searching their class list for matchClass. If a match is found, the contents is replaced.

    jsFiddle Example, using Vanilla JS (i.e. no framework)

提交回复
热议问题