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

Asked

Viewed 43 times

2

I’m making a site using wordpress and bootstrap.

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

I don’t know what happens with jquery selectors, they work in pure php, but not in wordpress.

I used a function to test which element I’m clicking

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

but with the dial body, nothing appears, only works when I put the selector '*'.

Does anyone know why this behavior?

  • Same thing, only works in pure php

  • Try using Document instead of body: $(document)

  • I discovered the error, js was loading before in head, now I do not know why js only worked with the '*'

1 answer

0

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

When using a specific selector, such as $("body").click(..., it is necessary that the element exists 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 an event click pointing to the 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 will show result:

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

In this third example, I will use the universal selector before the div and will show that the div was 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 not yet existing in the DOM is using the method .on(). See that the script is positioned before the 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.