Below mentioned is the way to get the element
by 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) {
}
}
}
I have onclick
and style
attribute with this Tag.
My query is, How can I remove/add the onclick/style
attribute in this tag using JavaScript
?
Below mentioned is the way to get the element
by 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) {
}
}
}
I have onclick
and style
attribute with this Tag.
My query is, How can I remove/add the onclick/style
attribute in this tag using JavaScript
?
- 1 Would you consider using JQuery for this task or you need only pure JS ? – Dmitry Reznik Commented Apr 16, 2012 at 10:29
- 2 why don't you use jquery class selector? – Okan Kocyigit Commented Apr 16, 2012 at 10:37
4 Answers
Reset to default 3HTML5 defines a method, getElementsByClassName(), that allows us to select sets of document elements based on the identifiers in their class attribute.
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() deletes a named attribute from this element. Attempts to remove non- existent attributes are silently ignored.
setAttribute()
This method sets the specified attribute to the specified value. If no attribute by that name already exists, a new one is created.
hasAttribute()
This method returns true if this element has an attribute with the specified name and false
otherwise.
https://developer.mozilla/en/DOM/element.removeAttribute
By using JQuery you could use class selectors and then remove associated attributes by using the removeattr function:
$('.className').removeAttr('click style')
To add and remove some class:
$('.className').addClass('className').removeClass('newlyaddedClass')
$(function(){
$(".className").removeAttr("onclick style");
});
http://jsfiddle/Curt/h6CT9/
var Tag = replaceContentInContainer('className');
for(var i = 0; i < Tag.length; i++){
Tag[i].removeAttribute('onclick');
Tag[i].removeAttribute('style');
}
update
I'm sorry, i saw your code incorrectly. I assumed your function was returning an array of elements with that classname... so, using your function:
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');
}
}
}