Home > Software engineering >  can't get the child of a div clicked
can't get the child of a div clicked

Time:11-30

i want to when i click on the div 'nav-item' the child tag a get clicked , i have try some way but it's not working for me

PS : i don't want to wrap the parent div with tag a

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

jquery :

$('.nav-item').click(function () {
  $(this).children('a').click();  
});

can anyone help please ?

CodePudding user response:

Have you tried to solve your request only using the css padding ?

.nav {display: flex;}
.item-parent a {
  padding: 8px;
}
<div class="nav">
  <div class="nav-item" data-nav-item="1">
    <div class="item-parent">
      <a href="https://mystore-men.com">MEN</a>
    </div>
  </div>
  <div class="nav-item" data-nav-item="2">
    <div class="item-parent">
      <a href="https://mystore-women.com">Women</a>
    </div>
  </div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can expand the clickable area of your <a> element to cover the entire parent element by using absolute positioning.

document.addEventListener("click", e => {
  if (e.target.tagName.toUpperCase() !== "A") {
    return;
  }
  e.preventDefault();
  alert(e.target.href);
});
.nav-item {
  position: relative;
  background-color: #eee;
  padding: 20px;
}

.nav-item .item-parent {
  background-color: #ccc;
  padding: 20px;
}

.nav-item a::before {
  content: " ";
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
<div class="nav-item" data-nav-item="1">
  <div class="item-parent">
    <a href="men">MEN</a>
  </div>
</div>
<div class="nav-item" data-nav-item="2">
  <div class="item-parent">
    <a href="women">Women</a>
  </div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You should use the find jquery method since find method returns all the descendant elements like child, grandchild and so on.

Here's the jquery code,

$('.nav-item').click(function () {
  $(this).find('a')[0].click();
});

The find method returns all the descendant a elements. I'm selecting the first one [0] and triggering the click event.

  • Related