0

I'm trying to get an element by class name, and after, remove it's class.

I wish to accomplish that using JavaScript only, no jQuery.

Here is what I've tried already:

<script>
  var changeController = function() {
    var removeClass = document.getElementsByClassName("selected-hr")[0];
    removeClass.classList.remove("selected-hr");
  }
</script>

<div class="col col-25 selected-hr">
  <a class="tb-header-link" onclick="changeController()">ALL</a>
</div>

EDIT 1: Fixed typo at changeController()

4
  • onclick="changeController()" Commented May 2, 2017 at 16:17
  • This works for me without any problem. Commented May 2, 2017 at 16:34
  • onclick="return changeController();" professionalism.. Commented May 2, 2017 at 16:35
  • code working fine Commented May 2, 2017 at 17:52

2 Answers 2

1

Pass this into changeController(), use parentNode property to reference the div. Place the <script> after the your markup (HTML) to ensure DOM is loaded before running script. Preferably before the </body> closing tag.

Snippet

a {text-decoration:none;}
.selected-hr {background:tomato;}
<div class="col col-25 selected-hr">
  <a href='#/' class="tb-header-link" onclick="changeController(this)">ALL</a>
</div>

<script>
  function changeController(ele) {
    var parent = ele.parentNode;
    parent.classList.remove("selected-hr");
  }
</script>

Sign up to request clarification or add additional context in comments.

Comments

0

Just mentioning the name of a variable does nothing (even if the variable points to a function).

You have to call it if you want to do anything with it. Add ().

onclick="changeController()"

3 Comments

Ok, that was a typo. I already fixed it, but the code is still not working.
@GreetingsFriend — Given that fix, it works for me: jsbin.com/tubuduh/1/edit?html,css,output
I just checked the console. changeController is not defined. The script is on a nested view just on top of the html(using angular-ui router). Where should i place the script?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.