nathan
nathan

Reputation: 43

<ul> <li> list items adding onclick

I'm trying to add onclick to my list items and get the href with pure JavaScript. I had it working from just a div but as soon as I added list items I was unable to get it to work.

var navBarDiv = document.getElementById("navbar");
var contentDiv = document.getElementById("content");

var navBarList = navBarDiv.getElementsByTagName("ul");

// Attach click listeners for each of the nav links.
for (var i = 0; i < navBarList.length; i++) {

    var navBarItems = navBarList[i].getElementsByTagName("li");
    for (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>

Upvotes: 1

Views: 3520

Answers (6)

Vts
Vts

Reputation: 51

Without using ES6

Array.prototype.slice.call(document.querySelectorAll('#navbar ul li a')).map(function(item) {
 item.addEventListener('click', function(e) {
 e.preventDefault();
 console.log("href", e.target.href);
 });
});
<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>

Using ES6

[...document.querySelectorAll('#navbar ul li a')]
.map((item) => {
 item.addEventListener('click', (e) => {
 e.preventDefault();
 console.log("href", e.target.href);
 });
});
<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>

jQuery

jQuery('#navbar ul li').click(function() {
console.log("href", $(this).attr('href'))
});

Upvotes: 1

Thomas
Thomas

Reputation: 2536

Try this one:

var navBarDiv = document.getElementById("navbar");
var contentDiv = document.getElementById("content");

var navBarLinks = navBarDiv.getElementsByTagName("a");

// Attach click listeners for each of the nav links.
for (var i = 0; i < navBarLinks.length; i++) {


    navBarLinks[i].addEventListener('click', function (e) {
        e.preventDefault();

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

        GetFileDoc(pageURL, function (doc) {
            contentDiv.innerHTML = doc.getElementById("content").innerHTML;
        });
    });
}

}

It's nearly the same except I filter directly to the anchor-tags and then there is a href attribute.

Upvotes: 1

Manoj Pilania
Manoj Pilania

Reputation: 666

Please try this code

  var navBarDiv = document.getElementById("navbar");
  var contentDiv = document.getElementById("content");

  var navBarList = navBarDiv.getElementsByTagName("ul");

  // Attach click listeners for each of the nav links.
  for (var i = 0; i < navBarList.length; i++) {

      var navBarItems = navBarList[i].getElementsByTagName("li");
      for (var j = 0; j < navBarItems.length; j++) {

          navBarItems[j].addEventListener('click', function (e) {
              e.preventDefault();
                        var pageURL = this.getElementsByTagName('a')[0].href;
              alert(pageURL);
               GetFileDoc(pageURL, function (doc) {
                 contentDiv.innerHTML = doc.getElementById("content").innerHTML;
               });
          });
      }
  }

Upvotes: 0

insider
insider

Reputation: 362

You are adding event to each li in the list. According to the rest of the code, espscialy the line this.attributes['href'].value you expect to have link element loaded. You can load all the link elements instead right away by using

navBarList[i].querySelectorAll("a");

which gives you all the inner links.

Upvotes: 1

prasanth
prasanth

Reputation: 22490

Try with

  1. a tag is the children of li so you need use querySelectorfor target the child element
  2. And simply use with element.href for getting href value

var navBarDiv = document.getElementById("navbar");
var contentDiv = document.getElementById("content");

var navBarList = navBarDiv.getElementsByTagName("ul");

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

  var navBarItems = navBarList[i].getElementsByTagName("li");
  for (var j = 0; j < navBarItems.length; j++) {

    navBarItems[j].addEventListener('click', function(e) {
      e.preventDefault();
      var pageURL = this.querySelector('a').href;
      console.log(pageURL)
      //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>

Upvotes: 1

David
David

Reputation: 218818

This appears to be the problem:

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

You're adding the click handler to the li element, not the a element. So there is no href attribute. I imagine there are two options:

  1. Drill into the element further to get the href of the child a element, or
  2. Add the click handler to the a element instead

For the first option, you might do something like this instead:

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

You'd want to put in some error checking of course, unless you're very confident that there will always be that first a element that you want.

For the second option, you might just modify what you're looping over. Perhaps something like this:

var navBarItems = navBarList[i].getElementsByTagName("a");

Assuming there are no other a elements in the hierarchy that you don't want to use for this.

Upvotes: 1

Related Questions