0

I am wondering if it is possible to find an element by the onclick function?

For example:

<a class = "calculator" onclick = add(number1,number2);

<a class = "calculator" onclick = add(number2, number3);

And I want to get the first one and the only difference is the onclick function so I thought thats the way I could differ them. Looks so far like this:

var elements = document.getElementsByClassName("calculator");

console.log(elements);

for (var i = 0; i <  elements .length; ++i) {
elementsSpecific = elements[i]. //The missing part

console.log(delementsSpecific);
 }
isherwood
  • 58,414
  • 16
  • 114
  • 157
user3361146
  • 103
  • 3
  • 9
  • I can't imagine why you'd ever need to do this. But for everyone's sake, don't use inline event handlers: http://stackoverflow.com/questions/15792498/is-it-bad-practice-to-use-inline-event-handlers-in-html – Ian Mar 06 '14 at 22:26

5 Answers5

2

You can, though I wouldn't recommend it. It's faster to use different ids. However, if you really want to do it this way...

var link = document.querySelector('a[onclick="add(number1,number2)"]');

If you don't understand it, read about querySelector

Oscar Paz
  • 18,084
  • 3
  • 27
  • 42
0

You can get the onclick function by using

elements[i].getAttribute('onclick');
Nicky Smits
  • 2,980
  • 4
  • 20
  • 27
0

This is a pretty poor way of targeting elements (what if the onclick value changes?) but if it's all you've got then you can use an attribute selector and querySelector:

var el = document.querySelector('a[onclick="add(number1,number2);"]');

I would definitely exhaust other avenues of selection before resorting to this, however.

Mitya
  • 33,629
  • 9
  • 60
  • 107
0

Without using js frameworks and making it for crossbrowser you can do this.

var as = document.getElementsByClassName('calculator');
var element = null;
for (var x = 0; x < as.length; x++) {
  if (as[x].getAttribute('onclick') == 'add(number2,number3)') {
    element = as[x];
    break;
  }
}

http://jsbin.com/feyaheji/1/edit?html,console

Daniel Rogi
  • 163
  • 7
0

document.querySelector is the holy grail of finding elements in the DOM:

HTML:

<a class = "calculator" onclick = "add(number1,number2);">First</>
<a class = "calculator" onclick = "add(number2, number3);">Second</>

JavaScript:

var d2 = document.querySelector('.calculator[onclick*=number2][onclick*=number3]');
var d1 = document.querySelector('.calculator[onclick*=number1][onclick*=number2]');

console.log('Second', d2);
console.log('First', d1);

Notice the [onclick*=number2] selector which matches elements with the attribute name onclick and the value containing number2

Tibos
  • 27,507
  • 4
  • 50
  • 64