1

function onClickEv(child){
  //change the class from div_className to div_newClass
  console.log(child);
}
<a href="page url" id="a_idName" target="_blank" onclick="onClickEv(this)" class="a_className">
   <div class="div_className">text here</div>
</a>

How can I change the class attribute value of div inside the anchor element in onclick event "onClickEv" in my external javascript. Is it possible?

Nilesh Khisadiya
  • 1,560
  • 2
  • 15
  • 27
ezekiel
  • 13
  • 5
  • Possible duplicate of [Change an element's class with JavaScript](https://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript) – Hash Jul 13 '17 at 03:30
  • Add `child.getElementsByTagName("div")[0].className = "div_newClassName";` this line in your `onClickEv` function. It will works. – Nilesh Khisadiya Jul 13 '17 at 06:30

2 Answers2

0

Assign an Id to your Div element and use below code to achieve this :

var element = document.getElementById("div-id");
if (element !== null) {
  if (element.className == "div_className") {
    element.className = "div_newClassName";
  } else {
    // add this else only in case you want to toggle the class
    element.className = "div_className";
  }
}
pritesh agrawal
  • 1,155
  • 8
  • 16
  • I have multiple anchor with a child div. What I want is to change the class attribute value of the one I click, that's why I use the **this** as the parameter of my function onClickEv(child). – ezekiel Jul 13 '17 at 04:02
0

You can change class name in javascript as shown below code snippet.

function onClickEv(child){
  //change the class from div_className to div_newClass
   
 child.getElementsByTagName("div")[0].className = "div_newClassName";

   console.log(document.getElementById("a_idName").innerHTML);
}
<a href="page url" id="a_idName" target="_blank" onclick="onClickEv(this)" class="a_className">
   <div class="div_className">text here</div>
</a>

OR

You can do it using JQuery addClass, removeClass function.

Replace below line in onClickEv function and add jQuery library in html header.

$("#a_idName div").removeClass('div_className').addClass('div_newClassName');
Nilesh Khisadiya
  • 1,560
  • 2
  • 15
  • 27