0 sec javascript replace

61 views Asked by At

I have a code it looks like this. It basicly replace ''php echo'' with an image. But... When i load or reload the page i can still see ''php echo'' i want that image to be loaded direcly in 0 sec so i dont need to see ''php echo'' and also load that image in 0 sec. /// Sorry for my bad english.

Video example: https://youtu.be/XFI7DIrlVcM

<td id="X"><?php echo $row['11']; ?></td>

<script>
var tdList = document.getElementsByTagName('td');
for(var i=0; i< tdList.length; i++){ 
  if(parseInt(tdList[i].innerHTML.trim())>= 0 && parseInt(tdList[i].innerHTML.trim())< 10 && tdList[i].getAttribute('id') == "X")
  tdList[i].innerHTML = '<img src="http://i.imgur.com/bgwZcHq.png">'
}
</script>

2

There are 2 answers

11
Scott Marcus On BEST ANSWER

Then remove the value from being the content of the td and put it on the td as a data attribute, which you can then retrieve in JavaScript with the dataset property.

<!-- Put the empty <img> element into the cell so that the DOM is built correct from the start -->
<td id="X" data-value="<?php echo $row['11']; ?>"><img id="replace" title=""></td>

<script>

// Get all the td elements in an array
var tdList = Array.prototype.slice.call(document.querySelectorAll("td"));

// Get a reference to the empty image element
var img = document.getElementById("replace");

// Loop over the array
tdList.forEach(function(td){
  var val = parseInt(td.dataset.value, 10);
  
  // Check the id first for better performance since we don't care 
  // about the value unless we have the right element:
  if(td.id === "X" && val >=0 && val < 10 ){
    // Now, we only have to update the image element, not rebuild the DOM
    replace.src = "http://i.imgur.com/bgwZcHq.png";
  }
});

</script>

10
Christian Santos On

There is no <td> being rendered on the page as <td>s are only valid in a very specific context: within a <tr> of a <table>, which is why your <td> is not being picked up at all.

If you change <td> to <span> and run the same code, you'll get the expected results:

var tdList = document.getElementsByTagName('span');
for(var i=0; i< tdList.length; i++){ 
  if(parseInt(tdList[i].innerHTML.trim())>= 0 && parseInt(tdList[i].innerHTML.trim())< 10 && tdList[i].getAttribute('id') == "X")
  tdList[i].innerHTML = '<img src="http://i.imgur.com/bgwZcHq.png" />'
}
<span id="X">1</span>