Search code examples
javascriptjqueryonclicklocation-href

Use Javascript onClick Event to go to href of a child element


Due some weirdness I'm stuck with using javascript to Jquery to get a link to work by clicking the a parent li element. Basically clicking anywhere on the li should take the user to the link of the a that is a direct child of it. What I have some far does not seem to work. The code:

<ul>
<li onclick="location.href='$(this).children('a:first').attr('href')';">
    <a href="http://example.com/">link</a>
    </li>
    </ul> 

Thank you!


Solution

  • When you put single quotes around the href, its seen as a string. Also, you used single quotes within other single quotes, which ends the string prematurely. It literally tries to go to the url "$(this).children(".

    Instead, remove the single quotes around the location.href

    <ul>
        <li onclick="location.href=$(this).children('a:first').attr('href');">
            <a href="http://example.com/">link</a>
        </li>
    </ul> 
    

    Also, you really shouldn't use inline scripts like this. It's much better to add a script tag to the bottom of the page and put a script in there that binds to the li's click event.