如何按类获取元素并在JavaScript中添加/删除属性?

时间:2012-04-16 10:25:01

标签: javascript jquery asp.net

下面提到了通过get the element

Class Name的方法
var Tag = replaceContentInContainer('className');

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

此标记包含onclickstyle属性。

我的查询是,如何使用onclick/style删除/添加此代码中的JavaScript属性?

4 个答案:

答案 0 :(得分:2)

HTML5定义了一个方法getElementsByClassName(),它允许我们根据类属性中的标识符选择文档元素集。

var elts = document.getElementsByClassName("className");

for(var e = 0; e < elts.length; e++) { // For each element
   var elt = elts[e];
   elt.removeAttribute("style");
   elt.removeAttribute("onclick");
}

的removeAttribute()
removeAttribute()从此元素中删除命名属性。尝试删除不存在的属性会被忽略。

的setAttribute()
此方法将指定的属性设置为指定的值。如果该名称的属性不存在,则会创建一个新属性。

hasAttribute()
如果此元素具有指定名称和false的属性,则此方法返回true 除此以外。

https://developer.mozilla.org/en/DOM/element.removeAttribute

答案 1 :(得分:1)

​$(function(){
    $(".className").removeAttr("onclick style");       
});​

http://jsfiddle.net/Curt/h6CT9/

答案 2 :(得分:1)

通过使用JQuery,您可以使用类选择器,然后使用removeattr函数删除关联的属性:

$('.className').removeAttr('click style')

添加和删除某些类:

$('.className').addClass('className').removeClass('newlyaddedClass')

答案 3 :(得分:0)

var Tag = replaceContentInContainer('className');
for(var i = 0; i < Tag.length; i++){
   Tag[i].removeAttribute('onclick');
   Tag[i].removeAttribute('style');
}

更新

对不起,我看到你的代码不正确。我假设你的函数返回了一个带有该类名的元素数组......所以,使用你的函数:

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