Arrow
Arrow

Reputation: 2904

How to get the id attribute of a dynamically-generated element?

How can I get the id attribute of a dynamically generated element when you don't know it's id? I am wanting to setup some eventListeners for about 2000 Checkbox's on a page.

I know I could call a function from within the element:

<input type="checkbox" id="{databaseResult.Value}" onclick="someFunction(this)" />

But I'm not allowed to use JavaScript, or references to it in my HTML. Pure JavaScript (or a language that compiles to it) is my only option.

The code I already have for some elements where I do know the id, is:

var tb = <HTMLInputElement>document.getElementById("tbox");

if(tb.addEventListener("", function (e) {
    sayHello(tb.value);
}, false));

Upvotes: 1

Views: 3105

Answers (1)

RobG
RobG

Reputation: 147413

Put a single listener on an ancestor element, say the body, and listen for events on that, e.g.:

<body onclick="handleClick(event);" ...>

and the function is:

function handleClick(evt) {
  var el = evt.target || evt.srcElement;

  if (el && el.type == 'checkbox') {
    alert(el.id);
  }
}

Of course you can add the listener dynamically, I've used inline for convenience.

Edit

To attach the listener dynamically, use an addEvent function to cope with IE and W3C event models:

function addEvent(el, evt, fn) {

  // W3C event model
  if (el.addEventListener) {
    el.addEventListener(evt, fn, false);

  // IE event model
  // Set this and pass event as first parameter
  } else if (el.attachEvent) {
    el.attachEvent('on' + evt, (function(el, fn) {
        return function() {fn.call(el, window.event);};
      })(el, fn)
    );
  }

  // Prevent circular reference
  el = null;
}

And call it as:

window.onload = function() {
  addEvent(document.body, 'click', handleClick);
}

Upvotes: 2

Related Questions