如何在JavaScript中按类获取元素? [英] How to Get Element By Class in JavaScript?

查看:324
本文介绍了如何在JavaScript中按类获取元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想替换html元素中的内容,所以我使用以下函数:

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>

以上效果很好,但问题是我在页面上有多个html元素替换内容。所以我不能使用id而是使用类。我被告知javascript不支持任何类型的内置get元素的类函数。那么如何修改上面的代码以使其适用于类而不是ID?

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。我不想为此使用jQuery。

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

推荐答案

此代码应适用于所有浏览器。

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

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

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示例,使用Vanilla JS(即没有框架)

这篇关于如何在JavaScript中按类获取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆