Luigi Gargioni
Luigi Gargioni

Reputation: 45

Select only the child of an element, identified by his class

How can I activate the click event only on the child of the element (identified by his class) that I clicked?

I try this but seems that active all the onclick event of the .a-collaps-button on the page (I have multiple .collaps-button and multiple .a-collaps-button)

<button class="collaps-button">
  <a href="#adminModal" class="a-collaps-button" data-toggle="modal" onclick="showModalContentjs('modificy')">Modificy</a>
</button>
$('.collaps-button').click(function () {
  $(this).children('.a-collaps-button').click();
});

For the CSS I do this and it works

$(function () {
  $('.collaps-button').hover(function () {
    $(this).children('.a-collaps-button').css('color', '#f44242');
    $(this).children('.a-collaps-button').css('text-decoration', 'none');
  }, function () {
    $(this).children('.a-collaps-button').css('color', 'white');
    $(this).children('.a-collaps-button').css('text-decoration', 'none');
  });
});

Upvotes: 0

Views: 73

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337656

Your major issue is that your HTML is invalid. You cannot nest clickable elements, ie. you cannot place an a element inside a button.

To fix this, remove the a element and simply attach whatever logic you execute on click of that a to the click event of the button instead. Also note that you should not be using outdated on* event attributes. Use unobtrusive event handlers, such as addEventListener() or jQuery's on() or event shortcut methods, such as click().

Also note that you shouldn't use JS to amend the UI. Your hover logic is much more suited to CSS. Try this:

$('.collaps-button').click(function() {
  showModalContentjs('modificy');
});

function showModalContentjs(foo) {
  console.log(foo);
}
.collaps-button {
  color: white;
  text-decoration: none
}
.collaps-button:hover {
  color: #f44242;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="collaps-button">Modificy</button>

Upvotes: 1

Related Questions