如何在 JavaScript 中按类获取元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3808808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:13:45  来源:igfitidea点击:

How to Get Element By Class in JavaScript?

javascript

提问by Taylor

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

我想替换 html 元素中的内容,因此我为此使用了以下函数:

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?

上面的方法很好用,但问题是我想要替换其中的内容的页面上有多个 html 元素。所以我不能使用 id 而是使用类。有人告诉我 javascript 不支持任何类型的按类函数的内置 get 元素。那么如何修改上面的代码以使其适用于类而不是 id 呢?

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

PS我不想为此使用jQuery。

采纳答案by Randy the Dev

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.

它的工作方式是循环遍历文档中的所有元素,并在它们的类列表中搜索matchClass. 如果找到匹配项,则替换内容。

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

jsFiddle 示例,使用 Vanilla JS(即无框架)

回答by ColdCold

Of course, all modern browsers now support the following simpler way:

当然,所有现代浏览器现在都支持以下更简单的方式:

var elements = document.getElementsByClassName('someClass');

but be warned it doesn't work with IE8 or before. See http://caniuse.com/getelementsbyclassname

但请注意,它不适用于 IE8 或更早版本。见http://caniuse.com/getelementsbyclassname

Also, not all browsers will return a pure NodeListlike they're supposed to.

此外,并非所有浏览器都会NodeList像他们应该的那样返回一个纯粹的。

You're probably still better off using your favorite cross-browser library.

您可能还是最好使用您最喜欢的跨浏览器库。

回答by Cristian Sanchez

document.querySelectorAll(".your_class_name_here");

That will work in "modern" browsers that implement that method (IE8+).

这将适用于实现该方法的“现代”浏览器(IE8+)。

function ReplaceContentInContainer(selector, content) {
  var nodeList = document.querySelectorAll(selector);
  for (var i = 0, length = nodeList.length; i < length; i++) {
     nodeList[i].innerHTML = content;
  }
}

ReplaceContentInContainer(".theclass", "HELLO WORLD");

If you want to provide support for older browsers, you could load a stand-alone selector engine like Sizzle(4KB mini+gzip) or Peppy(10K mini) and fall back to it if the native querySelector method is not found.

如果您想为旧浏览器提供支持,您可以加载一个独立的选择器引擎,如Sizzle(4KB mini+gzip) 或Peppy(10K mini),如果找不到原生的 querySelector 方法,则回退到它。

Is it overkill to load a selector engine just so you can get elements with a certain class? Probably. However, the scripts aren't all that big and you will may find the selector engine useful in many other places in your script.

加载选择器引擎只是为了获取具有特定类的元素是否太过分了?大概。然而,脚本并不是那么大,您可能会发现选择器引擎在脚本的许多其他地方都很有用。

回答by kta

A Simple and an easy way

一个简单的方法

var cusid_ele = document.getElementsByClassName('custid');
for (var i = 0; i < cusid_ele.length; ++i) {
    var item = cusid_ele[i];  
    item.innerHTML = 'this is value';
}

回答by afsantos

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

我很惊讶没有使用正则表达式的答案。根据jsPerf 测试,这几乎是安德鲁的答案,使用RegExp.test而不是String.indexOf,因为它似乎对多个操作的性能更好。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.");

回答by Dagg Nabbit

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;
}

回答by Roger Causto

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

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

回答by thornjad

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

我认为这在最初被问到时不是一个有效的选项,但您现在可以使用document.getElementsByClassName('');. 例如:

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

See the MDN documentationfor more.

有关更多信息,请参阅MDN 文档

回答by Daniel H?if?dt

jQuery handles this easy.

jQuery 处理这个很容易。

let element = $(.myclass);
element.html("Some string");

It changes all the .myclass elements to that text.

它将所有 .myclass 元素更改为该文本。

回答by KeatsKelleher

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

会工作