Click anywhere in the <li> and run href from <a>

Asked

Viewed 2,837 times

0

It is possible to visualize that the <a>is clickable ie, I click on it and it redirects me to another location for example, but I would like to know how I do so that it is possible to click anywhere from <li> to take place the redirect and not only in the <a>

ul {
  list-style-type: none;
  text-align:center;
}

ul li {
  width: 200px;
  height: 50px;
  border: 1px solid black;
}

ul li:hover {
  background: gray;
}
<ul>
  <li> <a href="#"> Um </a> </li>
  <li> <a href="#"> Dois </a> </li>
  <li> <a href="#"> Tres </a> </li>
</ul>

No matter where I click inside the <li> he would execute the href within the <a>

2 answers

1

Place the onclick event on li:

 ul {
      list-style-type: none;
      text-align:center;
    }

    ul li {
      width: 200px;
      height: 50px;
      border: 1px solid black;
    }

    ul li:hover {
      background: gray;
    }
    
    li { cursor: pointer; }
<ul>
  <li onclick="location.href = '/';"> Um </li>
  <li onclick="location.href = '/questions/272339/clicar-em-qualquer-local-do-li-e-executar-o-href-de-a';"> Dois </a> </li>
  <li onclick="location.href = '/questions/272336/validar-tamanho-da-senha';"> Tres </a> </li>
</ul>

  • That’s kind of a gambit right? Not according to the semantics right?

  • I don’t know, we have image link, div link and so on. It works?

  • I’m not talking about the link itself but about the way to fill the <li>, I’ll see if I can find another method, that I use <li> </a> </a> </li> and can perform this task, if I can’t get it right in your answer! Thanks for the help.

  • Do so: <li onclick="Location.href = 'https://answall.com/';">click</li>

  • The element ul wait only li as children. Any other element breaks semantics and leaves HTML invalid according to W3C. Although it usually works due to current implementations of browsers, it is highly recommended that this be avoided, since browsers can fix this at any time and which search system penalizes the page for not being the standards.

  • @Andersoncarloswoss, convincing explanation, I edited question

Show 1 more comment

1


Expand the <a> for the entire area of <li> with CSS:

ul li a{
   display: inline-block;
   width: 100%;
   height: 100%;
}

Example:

ul {
  list-style-type: none;
  text-align:center;
}

ul li {
  width: 200px;
  height: 50px;
  border: 1px solid black;
}

ul li:hover {
  background: gray;
}

ul li a{
   display: inline-block;
   width: 100%;
   height: 100%;
}
<ul>
  <li> <a href="javascript:alert('um')"> Um </a> </li>
  <li> <a href="javascript:alert('dois')"> Dois </a> </li>
  <li> <a href="javascript:alert('tres')"> Tres </a> </li>
</ul>

  • That there worked right, just have to be careful with the padding of <li> and use padding only in <a>, Thanks for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.