Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selector only working after inspecting/selecting element

I have this code here:

$(document).ready(function() {
    debugger;
    $("div[id^='stage_']").click(function (e) { alert('Hello'); });
});

The weird thing I can't explain is, that when I execute the selector once I'm in the console when reaching the debugger statement, it returns an empty array, []

But when I step out and go on the page, then hit Ctrl-Shift-C in Chrome to start inspecting and click on some of the div's that have the ID I'm looking for then execute the selector again in the console, now I have the elements I'm expecting.

I have even tried this here so to validate whether it was an async. loading issue (this is a system over which I don't have all the control). but still, when reaching the debugger, the selector doesn't work - even after waiting 10 seconds (which then I'm pretty sure the div's are there). I still have to go in inspector so jQuery recognize the elements.

$(document).ready(function() {
    //debugger;
    setTimeout(function() {
        debugger;
        $("div[id^='stage_']").click(function (e) { alert('allo'); });
    }, 10000);
});

Why would jQuery only be aware of elements that I've clicked on with Chrome's inspector ?

like image 558
Francis Ducharme Avatar asked Jul 13 '16 16:07

Francis Ducharme


2 Answers

I know it's a bit late but when you open Dev Tools in Chrome the execution context is set to top. If your controls are located within an iFrame, that is a different context, not accessible from top. Use the dropdown to select your iFrame's context and your jQuery will return an element.

The reason it works when you inspect an element, is Chrome has selected the execution context for you already.

enter image description here

Discussion about iFrame context in Dev Tools

like image 128
strattonn Avatar answered Nov 15 '22 04:11

strattonn


Using the "on", it works even if the element exists after the page loads.

$(document).ready(function(){ 
  //$("div[id^='stage_']").click( function (e) { alert('Hello'); });
  $("body").on('click','div[id^="stage_"]', function (e) { alert('Hello'); });
  $('body').html('<div id="stage_1">teste1</div>' +
                  '<div id="stage_2">teste2</div>' +
                  '<div>blabla</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

doc: http://api.jquery.com/on/

like image 1
Guilherme IA Avatar answered Nov 15 '22 05:11

Guilherme IA