0

Seems I have a problem using jQuery when I try to select an element included in a div with a bootstrap class.

The code is this:

    <div class="sec">
  <div class="dropdown">
        <h4>Management</h4><hr>
        <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
            Staff <span class="caret"></span>
        </button>
        <ul class="dropdown-menu">
            <li><a href="#" data-intrf="dir-01-01" >List</a></li>
            <li><a href="#" data-intrf="dir-01-02">Register</a></li>
            <li><a href="#" data-intrf="dir-01-03">Categories</a></li>
            <li class="divider"></li>
            <li><a href="#" data-intrf="dir-01-04">Messages</a></li>
        </ul>
</div></div>

jQuery code is:

$('#secInterf').on("click", 'a[data-intrf]', function(){
        alert('What Ever');
});

The html code (div with class="sec") is placed as dynamic content within a div (with id="secInterf") in the main page. The problem is that it seems that jQuery can no recognize the anchor with attribute data-intrf.

I had no problem with other dynamic content placed in the same div (#secInterf); so, I don't know if it's some kind of conflict between jQuery and Bootstrap or if I'm using a wrong selector to get the anchor with attribute data-intrf.

Thanks in advance.

MatCat
  • 13
  • 4

2 Answers2

0

trying to use this code ..

$(document).on('click','#Selector' function(){ console.log('What you want '); //it's better then alert (i think). });

0

Try to exchange the first selector like:

$(document.body).on('click', 'a[data-intrf]', function(){ 
   alert('What Ever'); }
);

Explanation: As you didn't share the full code but just an except I can just speculate but a possible reason why selecting it by #secInterf didn't work for you is that the element was not there on the initial page load (you inserted it dynamically too).

Using body or document as the first selector for delegated events should always work. It's just not best practice as you should just try to use a selector closer to your dynamic element because of performance reasons as also stated here: https://api.jquery.com/on/#direct-and-delegated-events

EDIT: As the OP stated it worked for him using the $('body') selector. Which is actually doing the same as the selector above. The difference is just a performance difference and in detail explained here Difference between $(document.body) and $('body') JQuery

Michael Troger
  • 3,336
  • 2
  • 25
  • 41