2012-04-16 48 views
1

下文提到的是Class Name如何通過類獲取元素並在JavaScript中添加/刪除屬性?

var Tag = replaceContentInContainer('className'); 

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

我有onclickstyle屬性與此標籤的方式來get the element

我的查詢是,如何使用JavaScript在此標記中刪除/添加onclick/style屬性?

+1

你會考慮使用JQuery這個任務,或者你只需​​要純JS? – 2012-04-16 10:29:33

+0

這取決於你。謝謝。 – Pankaj 2012-04-16 10:30:29

+2

爲什麼你不使用[jquery類選擇器](http://api.jquery.com/class-selector/)? – ocanal 2012-04-16 10:37:42

回答

2

通過使用JQuery,你可以使用類選擇,然後刪除相關屬性通過使用removeattr功能:

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

添加和刪除一些類:

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

感謝您的回覆。我實際上必須添加像這樣的'Previous'類,並且只刪除'newaddedclass'。 – Pankaj 2012-04-16 10:44:58

+1

在這種情況下,您可以使用jQuery中的removeClass方法。 – apnerve 2012-04-16 10:46:16

+0

正確。這裏是示例鏈接http://api.jquery.com/removeClass/ – Pankaj 2012-04-16 10:49:02

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'); 
     } 
    } 
} 
+0

它不工作。你可以檢查你的一面。沒有在'r'行顯示任何'length'(var i = 0; i Pankaj 2012-04-16 10:36:13

+0

它顯示運行時錯誤。 – Pankaj 2012-04-16 10:58:18

+0

現在試試吧,請 – 2012-04-16 11:43:41

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

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

+0

爲什麼downvote? – Curt 2012-04-16 10:44:34

+1

沒有必要使用循環。 '$('className')。removeAttr('onclick style')'就夠了。 – apnerve 2012-04-16 10:44:50

+0

考慮到您的解決方案,這是更好,更高效。這只是來自JSfiddle鏈接的更新。 HTTP://的jsfiddle。net/h6CT9/2/ – Joberror 2012-04-16 10:44:52

0

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()
如果此元件具有指定名稱的屬性和假 否則此方法返回true。

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

+1

問題是基於刪除元素的屬性,而不是選擇元素...請在發佈解決方案前閱讀問題 – Joberror 2012-04-16 10:55:25

+0

好吧,有方法可以刪除和設置屬性,而無需使用jQuery。 – undefined 2012-04-16 11:02:54