JavaScript: addEventListener not running -


learning javscript , trying trigger click event.

i'm not sure i'm doing wrong following doesn't seem work.

jsfiddle

http://jsfiddle.net/73e7h/1/

html

<ul>     <li id="nav-item-39">         <a href="#">visit</a>     </li>  <ul> 

js

var $visit = document.getelementbyid('nav-item-39').firstchild;  $visit.addeventlistener('click', function() {     print('hello'); }); 

the firstchild text node containing whitespace after end of li start tag , beginning of link. need first child that's element.

on many browsers, that's firstelementchild, if need support older browsers may need loop.

fiddle (using alert rather print)

another option use queryselector, available on modern browsers (even ie8 — of course, ie8 doesn't have addeventlistener):

var $visit = document.queryselector('#nav-item-39 a');  $visit.addeventlistener('click', function() {     print('hello'); }); 

that finds first a element that's descendant of #nav-item-39. if want require it's direct child instead, use selector string "#nav-item-39 > a" instead.

fiddle

(just completeness: queryselector finds first matching element , returns [or null if no match]. there's queryselectorall finds matching elements , returns static nodelist.)


side note: print, unless override (and don't think in fiddle), window.print opens browser's print dialog.


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -