Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the value of the clicked li element

First of all I'm adding an EventListener to the ul, as follows:

action_list_ul.addEventListener("click", set_ua_value, false);

The set_ua_value job is to:

• Listen to every click made on the ul childs (li elements) • get the value (innerHTML?) of the a tag inside the clicked li

<ul id="action-list">
<li><a href="#">foo</a></li>
<li><a href="#">bar</a></li>
</ul>

In case foo was clicked on, I need to retrieve the "foo" string.

Since I'm fairly new to javascript, I'm not sure how to get the actual "this" of the clicked li.

I do not want to use jQuery. Thanks :)

like image 574
elad.chen Avatar asked Dec 09 '25 10:12

elad.chen


2 Answers

A quick and dirty way is to bind the event to the list, and filter by anchor tags:

JS

var action_list_ul = document.getElementById('action-list');
action_list_ul.addEventListener("click", set_ua_value, false);

function set_ua_value (e) {
  if(e.target.nodeName == "A") {
       console.log(e.target.innerHTML);
    }

}

JS Bin

Alternately, you can filter by LI, and access the anchor through firstChild or childNodes[0].

like image 120
Nick Tomlin Avatar answered Dec 11 '25 23:12

Nick Tomlin


Use something like:

var win = window, doc = document, bod = doc.getElementsByTagName('body')[0];
function E(e){
  return doc.getElementById(e);
}
function actionListValue(element, func){
  var cn = element.childNodes;
  for(var i=0,l=cn.length; i<l; i++){
    if(cn[i].nodeType === 1){
      var nc = cn[i].childNodes;
      for(var n=0,c=nc.length; n<c; n++){
        if(nc[n].nodeType === 1){
          nc[n].onclick = function(){
            func(this.innerHTML);
          }
        }
      }
    }
  }

}
actionListValue(E('action-list'), set_ua_value);
like image 25
StackSlave Avatar answered Dec 12 '25 00:12

StackSlave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!