How to Get Element By Class in JavaScript?

前端 未结 11 2370
南旧
南旧 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:36

    This should work in pretty much any browser...

    function getByClass (className, parent) {
      parent || (parent=document);
      var descendants=parent.getElementsByTagName('*'), i=-1, e, result=[];
      while (e=descendants[++i]) {
        ((' '+(e['class']||e.className)+' ').indexOf(' '+className+' ') > -1) && result.push(e);
      }
      return result;
    }
    

    You should be able to use it like this:

    function replaceInClass (className, content) {
      var nodes = getByClass(className), i=-1, node;
      while (node=nodes[++i]) node.innerHTML = content;
    }
    

提交回复
热议问题