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>
3
  • Is this is what you are looking for ? stackoverflow.com/a/3774720/1172872 Commented Apr 23, 2013 at 7:03
  • You have getElementById , yet no ID in your buttons. Commented Apr 23, 2013 at 7:03
  • sorry i am putting it Commented Apr 23, 2013 at 7:05

3 Answers 3

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

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

Comments

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

Comments

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

Comments

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.