user1461607
user1461607

Reputation: 2770

Attach event to child elements

<div class="tabContainer">
  <ul class="Tabs" id="tabset">
    <li id="tab1" class="selected" onclick="tabs(this)">Home</li>
    <li id="tab2" onclick="tabs(this)">Tab 2</li>
    <li id="tab3"  onclick="tabs(this)">Tab 3</li>
  </ul>
</div>

I want to remove onclick="tabs(this)" and turn it into an event. How can I do this? Currently the below code is my solution which isn't working.

var h=$("tabset").children;
for (i=0;i<h.length;i++) h[i].onclick=tabs(this);

Oh and no jquery please, but var $ = function(x){return document.getElementById(x)}; NOTE: I need the (this) part.

Upvotes: 1

Views: 2939

Answers (2)

David Thomas
David Thomas

Reputation: 253368

I'd suggest:

var lis = document.getElementById('tabset').getElementsByTagName('li');
for (var i = 0, len = lis.length; i < len; i++){
    lis[i].onclick = tabs; // inside the function 'this' will refer to the node.
}

JS Fiddle demo.

Though you could assign the click-handler to the containing ul element:

var list = document.getElementById('tabset');
tabset.onclick = list.addEventListener('click', function(e){
    tabs(e.target);
}, false);

JS Fiddle demo.

You could, now I see what you're doing with your function, avoid using getElementById() and simply chain:

$('tabset').addEventListener('click', function(e){
    tabs(e.target);
}, false);

JS Fiddle demo.

With jQuery, as you appeared (prior to an edit) to be trying to use:

$('#tabset li').click(function(){
    tabs(this);
});

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039060

You seem to be using some $ function in your code which is not standard. For example if you are using jQuery your code could look like this:

$('#tabset li').on('click', tabs);

If you don't want to use jQuery then you will have to adapt your selector:

var h = document.getElementById('tabset').getElementsByTagName('li');
for (var i = 0; i < h.length; i++) {
    h[i].onclick = tabs;
}

or since you declared:

var $ = function(x){
    return document.getElementById(x)
};

you could also use:

var h = $('tabset').getElementsByTagName('li');
for (var i = 0; i < h.length; i++) {
    h[i].onclick = tabs;
}

Upvotes: 2

Related Questions