Atomixx Atomixx - 26 days ago 14
HTML Question

JQuery Style not applying to Table loaded through Javascript

I'm trying to select any elements containing a particular text string and make their background color yellow. In my example, the javascript effects the HTML table, but doesn't seem to effect the table that is loaded through Javascript. I've tried putting the script at the end/ making the script run last but I just can't seem to wrap my head around this.

fiddle: http://jsfiddle.net/p2yLcsw0/47/

<html>
<body>

<div class="sheetstotables"></div>
<script type="text/javascript">
var tableId = "9OD4Y"
var x = document.createElement("script"); x.type = "text/javascript"; x.async = true;
x.src = "http://www.sheetstotables.com/get_table.js";
var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(x, s);
</script>

<table>
<tr>
<th>cy</th>
<th>cy</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>GK</td>
</tr>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".windowbg td:contains(GK)").css("background-color", "yellow");
});
</script>

</body>

</html>

Answer Source

The problem is that your script execute before that your table be loaded the solution is to make your script to wait your table to load for this use setTimeout function like this:

$(document).ready(function(){
    setTimeout(function() {
 $("td:contains(GK)").css("background-color", "yellow");
}, 3000)

});