0
votes

Basically I want to do something like this:

<my-root-element id="myID">
    <button id="some-id">Occupy The Universe</button>
    <div id="x" class="class-1 class-1a">
        <div id="y" class="class-3">
        <p>Rabit hole</p>
    </div>
</div>
</my-root-element>

let rootEl = document.getElementById(myID);
rootEl.addEventListener('click', function(e) {
    if (e.target && e.target.matches('button#some-id')) {
        console.log("Did something nasty");
    } else if (e.target && e.target.matches('.class-1.class-1a') || e.target && e.target.matches('.class-1.class-1a > .class-3')) {
        console.log("Was there");
    }
});

It looks for me that class nesting is not working, but maybe I'm missing something? I would like to do this in one IF as both things do the same thing. It looks like querySelector supports nested classes, but can't figure out, how to implement it there.

2
Well your code will make the tests on the element, but without knowing what your HTML actually looks like it's impossible to say whether those selectors are correct or not.Pointy
It's not entirely clear what you want to do. You may want to try wrapping your logical conditions in parentheses; i.e. if ((e.target && e.target.matches('.class-1.class-1a')) || (e.target && e.target.matches('.class-1.class-1a > .class-3'))) {Heretic Monkey
@HereticMonkey that will not make any difference at all; that's already how the expression will be parsed because && binds more tightly than ||.Pointy
@Pointy I didn't say it would make a difference, I just suggested they may want to. Makes things easier to read.Heretic Monkey
Well what would help would be to make the e.target test just once and then parenthesize the || subexpression. However all of that is irrelevant if the selectors are incorrect anyway :)Pointy

2 Answers

0
votes

Looks like simple styling for #x helped. An no more needed that || part.

> * {
    pointer-events: none;
}
0
votes

The solution that worked for me is given below Now when I click on Image or Profile button text it appears and toggle

/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function userProfile() {
    document.getElementById("myDropdown").classList.toggle("show");
  }
  
  // Close the dropdown if the user clicks outside of it
  window.onclick = function(event) {
    if (!event.target.matches(['.dropbtn', '.profile'])) {
      var dropdowns = document.getElementsByClassName("dropdown-content");
      var i;
      for (i = 0; i < dropdowns.length; i++) {
        var openDropdown = dropdowns[i];
        if (openDropdown.classList.contains('show')) {
          openDropdown.classList.remove('show');
        }
      }
    }
  }