Body selector does not work in wordpress jquery, only the '*'

2

I'm making a website using wordpress and bootstrap.

I initially made the site in php and converted to a wordpress theme.

I do not know what happens to the jquery selectors, they work in pure php, but not in wordpress.

I used a function to test which element I am clicking

$( "body" ).click(function( event ) {
  alert( "clicked: " + event.target.nodeName );
});

But with the body selector, nothing appears, it only works when I put the '*' selector.

Does anyone know why this behavior?

    
asked by anonymous 24.05.2018 / 03:09

1 answer

0

This happens because the universal selector "*" ( see documentation ) enables click on elements not yet loaded in the DOM, because it selects just any "element", regardless of whether it was loaded in the DOM, because it is not specific, means anyone .

When using a specific selector such as $("body").click(... , the element must exist in the DOM, otherwise the event will not take effect because at the time of script execution the element has not yet been rendered and added to the DOM.

In this first example I will create a click event pointing to div before it is loaded into the DOM. See that nothing happens:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>$("div" ).click(function( event ) {
  console.log( "clicked: " + event.target.nodeName );
});
</script>
<div>Clique aqui. Nada irá acontecer!</div>

In this second, I will position the script after the element, and it will show result:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div>Cliqueaqui.</div><script>$("div" ).click(function( event ) {
  console.log( "clicked: " + event.target.nodeName );
});
</script>

In this third example, I'll use the universal selector before div and show that div has been clicked:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>$("*" ).click(function( event ) {
  console.log( "clicked: " + event.target.nodeName );
});
</script>
<div>Clique aqui</div>

Another example that selects an element that does not yet exist in the DOM is using the .on() method. Note that the script is positioned before div :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>$(document).on("click", "div", function( event ) {
  console.log( "clicked: " + event.target.nodeName );
});
</script>
<div>Clique aqui</div>
    
24.05.2018 / 06:31