Your question as asked has multiple issues, and I'm assuming it's intended to be pseudocode, because it wouldn't even get as far as returning 'Hey' as written.
Firstly, I believe you're intending to use getElementByClassName, not 'getElementByClass'
Secondly, I think you want textContent
, not value
from the clicked element.
But as far as your problem, I think the issue is that you're calling:
document.getElementByClassName('but').value
Which effectively means that when rev() is called, it searches the document for ALL instances of .but
and looks for an object property called 'value'...
Instead, you want the textContent of just the element whose onclick
event has been triggered. To do that, you need to capture the event in your event handler function, rev()
Here's a way you can attach rev()
function as the 'click' event handler to all items in the document with the className .but
-- note that I removed the function rev() from the HTML onclick attribute, and instead it gets added do each element when .map()
loops through and calls button.addEventListener()
:
var buts = document.getElementsByClassName('but');
var buttons = Array.prototype.slice.call(buts);
buttons.map(function(button) {
button.addEventListener('click', rev);
});
function rev(e) {
// This is the element targeted by the current event.
var element = e.target;
// Assuming you want 'Hey', 'Hey2', etc.
var value = element.textContent;
alert(value);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<a href="#" class="but">Hey</a>
<a href="#" class="but">Hey2</a>
<button class="but">hey</button>
<button class="but">NOww</button>
</body>
</html>
The short answer is really: to get some specific value from an element which is listening for an event, you have to capture the event object -- the 'target' property of the event object is the element listening on the event.