How to Get Element By Class in JavaScript?

2018-12-31 04:32发布

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

function ReplaceContentInContainer(id,content) {
   var container = document.getElementById(id);
   container.innerHTML = content;
}

ReplaceContentInContainer('box','This is the replacement text');

<div id='box'></div>

The above works great but the problem is I have more than one html element on a page that I want to replace the contents of. So I can't use ids but classes instead. I have been told that javascript does not support any type of inbuilt get element by class function. So how can the above code be revised to make it work with classes instead of ids?

P.S. I don't want to use jQuery for this.

标签: javascript
10条回答
明月照影归
2楼-- · 2018-12-31 05:08

var elems = document.querySelectorAll('.one');

for (var i = 0; i < elems.length; i++) {
    elems[i].innerHTML = 'content';
};

查看更多
旧时光的记忆
3楼-- · 2018-12-31 05:08

I think something like:

function ReplaceContentInContainer(klass,content) {
var elems = document.getElementsByTagName('*');
for (i in elems){
    if(elems[i].getAttribute('class') == klass || elems[i].getAttribute('className') == klass){
        elems[i].innerHTML = content;
    }
}
}

would work

查看更多
流年柔荑漫光年
4楼-- · 2018-12-31 05:09

I assume this was not a valid option when this was originally asked, but you can now use document.getElementsByClassName('');. For example:

var elements = document.getElementsByClassName(names); // or:
var elements = rootElement.getElementsByClassName(names);

See the MDN documentation for more.

查看更多
孤独寂梦人
5楼-- · 2018-12-31 05:10

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;
}
查看更多
登录 后发表回答