Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get Element By Class and add/remove attribute in 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 ?

like image 860
Pankaj Avatar asked Sep 06 '26 07:09

Pankaj


2 Answers

HTML5 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.org/en/DOM/element.removeAttribute

like image 127
undefined Avatar answered Sep 07 '26 19:09

undefined


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')
like image 38
Dmitry Reznik Avatar answered Sep 07 '26 20:09

Dmitry Reznik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!