2

In Html file,I have many statements like this :

<li class="menu"><a href="#">1st menu</a></li>

And in javascript file,I have code like this :

1. function onload()
2. {
3.  var lists=document.getElementsByTagName("li");
4.  for(var i=0;i<lists.length;i++){
5.      if(lists[i].className=="menu"){
6.          lists[i].a.onclick=genmenu;
7.      }
8.  }
9. }

function genmenu(){
    alert("this is an alert");
    return false;
}

Problem is, if i click on the link '1st menu', it doesn't show alert. But if i change the line 6 and write:

lists[i].onclick=genmenu;

Then this link works and show alert.

My Question, Why line 6 (lists[i].a.onclick=genmenu;) does'nt work? Isn't it a valid code?

3 Answers 3

2

You cannot access nested elements as members of another element:

lists[i].a

This is looking for a member of the list[i] element with a name of a - it's not looking for an anchor within it. If you wanted the anchor, you'd write:

list[i].getElementsByTagName("a")[0];
Sign up to request clarification or add additional context in comments.

Comments

1

a is not a property of li, it is a nested tag. You'd have to use

lists[i].getElementsByTagName('a')[0];

As a side note, be careful with if(lists[i].className=="menu") because if one of your li's class is "menu otherClass" it will no longer work. jQuery has a good method to handle this: hasClass() but it'd be easy to write something similar if you're not using jQuery.

3 Comments

Thank you too for Quick feedback
In fact, there's already something rather similar to jQuery's selection stuff...document.querySelectorAll('li.menu a[href]') will give you all the links inside a list item with a class of 'menu'. Difference being, (1) jQuery works in IE7 :P, and (2) jQuery adds pseudo-selectors and such that aren't present in some versions of CSS.
querySelectorAll is part of the DOM standard and available on most modern browsers without the need to load JQuery. See developer.mozilla.org/en/DOM/document.querySelectorAll
0

On modern browsers your code can be simpler and more efficient:

function onload () {
   var links = document.querySelectorAll ('li.menu a[href]');
   for (var i= links.length; i--;) {
     links[i].addEventListener ('click', genmenu, false);
   }
}

function genmenu () {
    alert ("this is an alert");
    return false;
}

For more information, see the documentation on querySelectorAll.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.