1

Hi i have a requirement where i need to show the class name of button which has been clicked using java script. there are many buttons with different class names.Any suggestion?

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myFunction()
{
var container = document.getElementById(id);
alert (container);
}
</script>
</head>
<body>


<button class="A" id="A" onclick="myFunction()">A</button>
<button class="B" id="B" onclick="myFunction()">B</button>
<button class="C" id="C" onclick="myFunction()">C</button>
<button class="D" id="D" onclick="myFunction()">D</button>

</body>
</html>
Ethen
  • 161
  • 3
  • 3
  • 16

3 Answers3

7

You can use the className property of the dom element to get the class name.

<button class="A" onclick="myFunction(this)">A</button>
<button class="B" onclick="myFunction(this)">B</button>
<button class="C" onclick="myFunction(this)">C</button>
<button class="D" onclick="myFunction(this)">D</button>

function myFunction(el) {
    alert (el.className);
}

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
2

Is this is what you are looking for ?

 window.onclick = function(e) {
     console.log(e); // then e.srcElement.className has the class
 }​

http://jsfiddle.net/M2Wvp/

https://stackoverflow.com/a/3774720/1172872

Community
  • 1
  • 1
sk8terboi87 ツ
  • 3,396
  • 3
  • 34
  • 45
1

try like

<button id="A" class="b" onclick="myFunction(this)">A</button>

and to access the classname

function myFunction(el)
{
    console.log(el.className);
}

here is a demo fiddle

Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101