JavaScript: addEventListener not running -
learning javscript , trying trigger click event.
i'm not sure i'm doing wrong following doesn't seem work.
jsfiddle
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.
(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
Post a Comment