Reputation: 708
if the code snippet is like this:
<div id="test">
<div>
<h3>First section</h3>
<ul>
<li><a href="http://example.com">Item 1</a></li>
<li><a href="http://example.com">Item 2</a></li>
<li><a href="http://example.com">Item 3</a></li>
</ul>
</div>
<div>
<h3>Second section</h3>
<ul>
<li><a href="http://example.com">Item 4</a></li>
<li><a href="http://example.com">Item 5</a></li>
<li><a href="http://example.com">Item 6</a></li>
</ul>
</div>
</div>
I have the id "test" of the first div. how can i get the innerhtml
of clicked items. like alert the answer "item 1" when <li><a href="http://example.com">Item 1</a></li>
is clicked. I already tried this following code
var ul = document.getElementById("test").getElementsByTagName('ul')[0];
ul.onclick = function(event) {
event = event || window.event;
var target = event.target || event.srcElement;
alert(target.getAttribute("href"));
};
This working good only for the first section ul. i need the same to happen for N uls. What will be the best method for this. Thanks in advance.
Note: In my project i can't use jquery. only javascript or YUI is supported
Upvotes: 0
Views: 2224
Reputation: 21
You can use Event Delegation to achieve the expected result.
event.target
//Get the object of the div#test
var testDiv = document.getElementById('test');
//Bind onclick event for the div#test object
testDiv.onclick = function(e) {
//Prevent the default href action (optional)
e.preventDefault();
//Check whether the target element is an Anchor tag
if (e.target.nodeName == 'A') {
alert(e.target.innerHTML);
}
}
<div id="test">
<div>
<h3>First section</h3>
<ul>
<li><a href="http://example.com">Item 1</a>
</li>
<li><a href="http://example.com">Item 2</a>
</li>
<li><a href="http://example.com">Item 3</a>
</li>
</ul>
</div>
<div>
<h3>Second section</h3>
<ul>
<li><a href="http://example.com">Item 4</a>
</li>
<li><a href="http://example.com">Item 5</a>
</li>
<li><a href="http://example.com">Item 6</a>
</li>
</ul>
</div>
</div>
Upvotes: 0
Reputation: 388316
Iterate over each ul
and add the click handler to it like
var uls = document.getElementById("test").getElementsByTagName('ul');
for (var i = 0; i < uls.length; i++) {
uls[i].addEventListener('click', clickHandler)
}
function clickHandler(event) {
event = event || window.event;
var target = event.target || event.srcElement;
alert(target.getAttribute("href"));
}
<div id="test">
<div>
<h3>First section</h3>
<ul>
<li><a href="http://example.com">Item 1</a></li>
<li><a href="http://example.com">Item 2</a></li>
<li><a href="http://example.com">Item 3</a></li>
</ul>
</div>
<div>
<h3>Second section</h3>
<ul>
<li><a href="http://example.com">Item 4</a></li>
<li><a href="http://example.com">Item 5</a></li>
<li><a href="http://example.com">Item 6</a></li>
</ul>
</div>
</div>
Upvotes: 4