0

I have this code:

<div class="d-none d-js-block"> ... </div>

How can I remove the class attribute using javascript selector. I'm using this code:

var element = document.getElementsByClassName("d-none d-js-block"); element.classList.remove("d-none d-js-block");

I'm also using this code:

`var element = document.getElementsByClassName("d-d-none d-js-block");
element.removeAttr("class");`

This code is not working too; How can I remove the class?

sarah miller
  • 163
  • 3
  • 14
  • There is no `removeAttr` method on HTMLCollections. Also, your element has the class `d-none` but you're looking for `d-d-none`. See the link question's answers for more, but if you're using jQuery, `$(".d-none.d-jsblock").removeClass("d-none d-jsblock");`. – T.J. Crowder Jul 07 '18 at 10:03
  • Removing the entire `class` attribute isn't usually your best bet, in case you want to have other, unrelated classes on the element later. (That's why I used `removeClass` above.) – T.J. Crowder Jul 07 '18 at 10:03

2 Answers2

1

You need to specify the comma separated class names in the remove() function. And also make use of querySelector() if you have only that one element to select and remove the classes:

var element = document.querySelector(".d-none.d-js-block");
element.classList.remove("d-none", "d-js-block");
.d-none.d-js-block{
  color: red;
}
<div class="d-none d-js-block">
 some HTML
</div>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

getElementsByClassName returns a collection.So you need to pass the index of the element in that collection.

Alternatively you can use querySelectorAll and use classList.remove

Here usage of setTimeout is just to demonstrate the removal of the class.In your code you can avoid this

var element = document.querySelectorAll('.d-js-block');
setTimeout(function() {
  element.forEach(function(item) {
    item.classList.remove("d-none");
    item.classList.remove("d-js-block");
  })

}, 3000)
.d-none {
  color: green;
}

.d-js-block {
  text-decoration: underline;
}
<div class="d-none d-js-block">
  test</div>
brk
  • 48,835
  • 10
  • 56
  • 78