javascript - <ul> <li> list items adding onclick -


i'm trying add onclick list items , href pure javascript. had working div added list items unable work.

var navbardiv = document.getelementbyid("navbar");  var contentdiv = document.getelementbyid("content");    var navbarlist = navbardiv.getelementsbytagname("ul");    // attach click listeners each of nav links.  (var = 0; < navbarlist.length; i++) {        var navbaritems = navbarlist[i].getelementsbytagname("li");      (var j = 0; j < navbaritems.length; j++) {            navbaritems[j].addeventlistener('click', function (e) {              e.preventdefault();                var pageurl = this.attributes['href'].value;                getfiledoc(pageurl, function (doc) {                  contentdiv.innerhtml = doc.getelementbyid("content").innerhtml;              });          });      }  }
<div id="navbar">      <ul>          <li><a href="\" class="active">homepage</a></li>          <li><a href="pages/about.html">about us</a></li>          <li><a href="#">gallery</a></li>          <li><a href="pages/contact.html">contact us</a></li>      </ul>  </div>

this appears problem:

var pageurl = this.attributes['href'].value; 

you're adding click handler li element, not a element. there no href attribute. imagine there 2 options:

  1. drill element further href of child a element, or
  2. add click handler a element instead

for first option, might instead:

var pageurl = this.getelementsbytagname("a")[0].attributes['href'].value; 

you'd want put in error checking of course, unless you're confident there first a element want.

for second option, might modify you're looping over. perhaps this:

var navbaritems = navbarlist[i].getelementsbytagname("a"); 

assuming there no other a elements in hierarchy don't want use this.


Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -