2

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!

0

3 Answers 3

7

You could simplify your code by moving not using onclick, but rather using a selector to target that node and have a click event there.

$(".myUl li").on("click", function() {
    location.href = $(this).children("a").attr("href");
});

But you really should solve this by using css. You can use display: block; on the <a> as well, and have that fill the content, add extra paddings and basically behave like a div but keep the linking capability.

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

1 Comment

Yeah I know this should be a css solution, but the actual page in question has some php that somehow is restricting the links from working normally, so as I'm unable to decipher it, I tried to use JS instead.
4

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.

Comments

1

replace with this

    <li onclick="location.href=$(this).children('a:first').attr('href');">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.