0

Learning Javscript and trying to trigger a click event.

I'm not sure what I'm doing wrong but the following doesn't seem to 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');
});

2 Answers 2

3

The firstChild is a text node containing the whitespace after the end of the li start tag and the beginning of the link. You need the first child that's an element.

On many browsers, that's firstElementChild, but if you need support for older browsers you may need a loop.

Fiddle (using alert rather than print)

Another option is to use querySelector, which is available on all modern browsers (even IE8 — but of course, IE8 doesn't have addEventListener):

var $visit = document.querySelector('#nav-item-39 a');

$visit.addEventListener('click', function() {
    print('hello');
});

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

Fiddle

(Just for completeness: querySelector finds the first matching element and returns it [or null if no match]. There's also querySelectorAll which finds all matching elements and returns a static NodeList.)


Side note: print, unless you override it (and I don't think you do in the fiddle), is window.print which opens the browser's Print dialog.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 - There's also .children[0], which may or may not have better support than .firstElementChild, I can't remember :-P
1

Try Using firstElementChild instead of firstChild. firstElementChild will defenitely return element, when firstChild can return text node also.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.