-2

I want to redirect on the click of the item

EX: class="nav-item" data-nav-item="1"

to the link which is defined in his child tag "a"

<div class="nav-item" data-nav-item="1">
  <div class="item-parent">
    <a href="https://mywebsite-men.com">MEN</a>
  </div>
</div>

<div class="nav-item" data-nav-item="2">
  <div class="item-parent">
    <a href="https://mywebsite-women.com">Women</a>
  </div>
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
magNif
  • 1
  • 2
  • Can't you just wrap the `div`s in the `a` tag ? – Seblor Nov 29 '21 at 13:39
  • Welcome to Stack Overflow! Visit the [help], take the [tour] to see what and [ask]. Please first ***>>>[Search for related topics on SO](https://www.google.com/search?q=click+div+go+to+link+in+div+site:stackoverflow.com)<<<*** and if you get stuck, post a [mcve] of your attempt, noting input and expected output using the [`[<>]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Nov 29 '21 at 13:41
  • @Seblor it will change the old design of css i don't want to do that – magNif Nov 29 '21 at 13:45

1 Answers1

0

You can use click to trigger click when the parent element is clicked

[...document.getElementsByClassName('nav-item')].forEach(item => {
  item.addEventListener('click', (e) => {
    item.querySelector('a').click()
  })

})
.nav-item {
  width: 50px;
  height: 20px;
  padding: 10px;
  border: 1px solid green;
  cursor: pointer;
}
<div class="nav-item" data-nav-item="1">
  <div class="item-parent">
    <a href="https://mywebsite-men.com">MEN</a>
  </div>
</div>

<div class="nav-item" data-nav-item="2">
  <div class="item-parent">
    <a href="https://mywebsite-women.com">Women</a>
  </div>
</div>
brk
  • 48,835
  • 10
  • 56
  • 78
  • what is inside the 3 points ... , sorry i am new on javascript , i put it like this ===> document.getElementsByClassName('nav-item')].forEach(item => { item.addEventListener('click', (e) => { item.querySelector('a').click() }) }) – magNif Nov 29 '21 at 13:57
  • `forEach` is an array method `document.getElementsByClassName('nav-item')` returns a collection but array method cannot be directly use on collection. That `...` is used to convert nodelist collection to array so that array methods can be used – brk Nov 29 '21 at 14:01
  • it's not working i put it like this ==> [...document.getElementsByClassName('nav-item')].forEach(item => { item.addEventListener('click', (e) => { item.querySelector('a').click() }) }) – magNif Nov 29 '21 at 14:05