Wasteland
Wasteland

Reputation: 5379

javascript - click on any li element

I've got an unordered list and a couple of li elements. Eventually, I will want to have the following functionality. If I click on any of the li elements, an appropriate content will appear in another div (depending on which li I clicked on). Now I'm stuck on kind of generalising the rule:

var li_group = document.getElementsByTagName('li');
// li_group produces an HTML collection, as reported in a browser:
// HTMLCollection [ <li>, <li>, <li>, <li> ]

li_group[1].addEventListener('click', function() {
    alert("hello world");
});

As you can see above, I can do it but when I specify a specific element, eg.li_group[0]. How would I abstract it so I get the following: Click on any of the li elements, and based on the content of the chosen li element, display something on the main div (eg. display the content of the clicked li element on the main div.

I hope it makes sense. Thank you.

Upvotes: 1

Views: 1769

Answers (2)

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28445

You can do something like following

var lis = document.getElementsByTagName("li");

for (var i = 0 ; i < lis.length; i++) {

    lis[i].addEventListener('click', function(event) {
        alert(event.target.textContent);
       // over here you can set the content in main div
    });

}

Upvotes: 2

Steven Brookes
Steven Brookes

Reputation: 894

Inside your click event you can use the 'this' keyword to access the clicked li. This way you can do:

document.getElementById('mainDiv').innerHTML = this.innerHTML

Upvotes: 1

Related Questions