I have a for loop in PHP that creates four div, each containing a img and p string, as below:
<div class="guest-tile-holder">
<img class="guest-tile" src="<?php echo($tile); ?>">
<p><span><?php echo($fn.' '.$ln); ?></span></p>
</div>
In jQuery, I want to colour every fourth p black, i.e. only the p string the fourth box created, as below:
$(document).ready(function() {
$('p:nth-child(4)').css('color', 'black');
});
What I would expect is that the PHP would pre-process, creating four div as above and then jQuery would colour black the p string in the fourth div. What is actually happening however is jQuery appears to be ignoring the PHP and colouring a p string that is another three p strings away in my HTML.
I was always led to believe that PHP would pre-process, therefore I don’t understand why jQuery appears to be running before the PHP has completed.
Can anybody tell me how I would get the jQuery to run after PHP has finished?
Your jQuery is correctly executed after your PHP code, it’s just that you’re not selecting the right
p.p:nth-child(4)will select the paragraph which is the 4th element in the hierarchy. For example, the firstpwould be the 3rd element since it is preceded by adivand animg. What you’re actually looking for is something likep:nth-of-type(4)or.guest-tile-holder:nth-child(4)or even using jQuery’s custom:eq()selector:(Since JavaScript arrays use zero-based indexing, the 4th element has index 3.)