I have a series of repeating HTML blocks on a page (over 200 times) that need to have some content tweaks made via some simple javascript. What I’ve done is use querySelectorAll to target all of the parent HTML elements and then when performing a loop of all of the HTML blocks on the page with this selector, I’ve used nested childNodes[x] to target the element of each block and to search for the letters ‘HD’ inside, before running an IF statement and subsequent content changes (in this case, adding some simple text to each block).
The problem which I face is that the same code block/function will need to be called multiple times, depending on various user functions within the page and the script breaks because after the script has run for the first time, it adds HTML into each code block and upsets the ordering of the childNodes.
Ideally, I would be able to select the child node within the loop of the parent selector by referencing the HTML tag (which would be ) or the class name that it carries. This way, I wouldn’t have to worry about childNodes ordering being disturbed.
Here is a trimmed example of the HTML block that repeats on the page:
<vm-tile-media-small class="tile">
<div class="tile-media-small">
<div class="tile-media-small__">
<img src="channel_img.png" alt="channel 1 HD">
</div>
<h5 class="ng-star-inserted">channel 1 HD</h5>
</div>
</vm-tile-media-small>
Here is my script which works the first time:
let small_tile = document.querySelectorAll('vm-tile-media-small.tile');
for (let i = 0; i < small_tile.length; i++) {
small_tile[i].childNodes[1].childNodes[2].innerText;
let hd_text = 'HD';
if (small_tile[i].textContent.includes(hd_text)) {
small_tile[i].classList.add('HD_channel');
let HD_banner = document.createElement('div');
HD_banner.className = 'HD_banner';
HD_banner.innerHTML = '<p>HIGH DEFINITION</p>';
small_tile[i].prepend(HD_banner);
} // ends IF
} // ends loop
Here is how the HTML outputs after the script is run:
<vm-tile-media-small class="tile">
<div class="HD_banner">
<p>HIGH DEFINITION</p>
</div>
<div class="tile-media-small">
<div class="tile-media-small__">
<img src="channel_img.png" alt="channel 1 HD">
</div>
<h5 class="ng-star-inserted">channel 1 HD</h5>
</div>
</vm-tile-media-small>
For what it’s worth, I did consider performing the querySelectorAll on the , but then I’d still have to do some trickery with the script to add my new HTML mark up to the parent of this element instead.