A guide to injecting HTML banner code with pure Vanilla Javascript

Looking for a solution to incorporate banner code dynamically into an existing block of HTML on a static page without altering the original code?

<div class="wrapper"><img class="lazyload" src="/img/foo01.jpg"></div>
<div class="wrapper"><img class="lazyload" src="/img/foo02.jpg"></div>
<div class="wrapper"><img class="lazyload" src="/img/foo03.jpg"></div>
<div class="wrapper"><img class="lazyload" src="/img/foo04.jpg"></div>
<div class="wrapper"><img class="lazyload" src="/img/foo05.jpg"></div>
<div class="wrapper"><img class="lazyload" src="/img/foo06.jpg"></div>
<div class="wrapper"><img class="lazyload" src="/img/foo07.jpg"></div>
<div class="wrapper"><img class="lazyload" src="/img/foo08.jpg"></div>
<div class="wrapper"><img class="lazyload" src="/img/foo09.jpg"></div>
<div class="wrapper"><img class="lazyload" src="/img/foo10.jpg"></div>
<div class="wrapper"><img class="lazyload" src="/img/foo11.jpg"></div>
<div class="wrapper"><img class="lazyload" src="/img/foo12.jpg"></div>
<div class="wrapper"><img class="lazyload" src="/img/foo13.jpg"></div>
<div class="wrapper"><img class="lazyload" src="/img/foo14.jpg"></div>
<div class="wrapper"><img class="lazyload" src="/img/foo15.jpg"></div>

To achieve this using Vanilla JavaScript, you need to inject banner code after every 5th, 15th, and 30th occurrence of

<div class="wrapper"></div>
.

The increase starts at 10 and follows a pattern where each subsequent number is the previous number plus the increment plus 5.

For example: 5, 15, 30, 50, 75, 105, etc.

Additionally, translating this mathematical formula into actual coding can be challenging.

Here's a sample banner code snippet that needs to be inserted:

<div id="banner5"><ins data-revive-zoneid="123" data-revive-id="f123123fd4f12d4f123d12"></ins><script async src="//adserver.com/asyncjs.php"></script></div>

<div id="banner15"><ins data-revive-zoneid="456" data-revive-id="f123123fd4f12d4f123d12"></ins><script async src="//adserver.com/asyncjs.php"></script></div>

<div id="banner30"><ins data-revive-zoneid="456" data-revive-id="f123123fd4f12d4f123d12"></ins><script async src="//adserver.com/asyncjs.php"></script></div>

The desired output would look like this:

[Updated HTML with banner codes injected]

If you're wondering how to handle this task efficiently, keep reading!

Answer №1

  • Utilize the [].forEach method for iterating through all elements with the class .wrapper
  • Use the parentNode.insertBefore function to add an element at a specific position

var start = 5,
            multiple = 5;
    var elements = document.querySelectorAll('.wrapper');
    [].forEach.call(elements, function (elem, index) {
        var elemt = '<span>' + (index + 1) + '</span>';
        var div = document.createElement('div');
        div.innerHTML = elemt;
        elem.appendChild(div.firstChild);
    });
    var counter = 1;
    [].forEach.call(elements, function (elem, index) {
        var localIndex = index + 1;
        if (localIndex == start) {

            var toAppendHTML = '<div id="banner' + start + '"><ins data-revive-zoneid="123" data-revive-id="f123123fd4f12d4f123d12"></ins>'+start+'\
                    <script async src="//adserver.com/asyncjs.php"><\/script>\
</div>';
            var divElement = document.createElement('div');
            divElement.innerHTML = toAppendHTML;
            insertAfter(divElement.firstChild, elements[index]);
            start += multiple * ++counter;
        }
    });

    function insertAfter(newNode, referenceNode) {
        referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
    }
<div class="wrapper">
    <img class="lazyload" src="/img/foo01.jpg">
</div>
<div class="wrapper">
    <img class="lazyload" src="/img/foo02.jpg">
</div>

... (more image wrappers here)

<img class="lazyload" src="/img/foo15.jpg">
</div>

... (more image wrappers here)

<img class="lazyload" src="/img/foo15.jpg">
</div>

Answer №2

Give this a shot ;)

<div class="container"><img class="lazyload" src="/img/image01.jpg"></div>
<div class="container"><img class="lazyload" src="/img/image02.jpg"></div>
<div class="container"><img class="lazyload" src="/img/image03.jpg"></div>

...

<script>
  var containers = document.getElementsByClassName('container');
  for(var i in containers)
  {
    if(i > 9)
    {
      if(i%5 == 0)
      {
        var div = document.createElement('div');
        div.id  = 'banner'+i;
        div.innerHTML = '<ins data-revive-zoneid="123" data-revive-id="f123123fd4f12d4f123d12"></ins>';
        containers[i].parentElement.insertBefore(div, containers[i]);
      }
    }
  }
</script>

Answer №3

To help kickstart your project:

You have the option to utilize document.getElementsByClassName for selecting elements by class name:

var boxes = document.getElementsByClassName('box');

You can also make use of Element.insertAdjacentHTML to add HTML into the DOM following an element:

anotherBox.insertAdjacentHTML(
    'beforebegin',
    '<p id="importantText">This is some important text.</p>'
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

You are unable to align a paragraph with a specific width in the center

I adjusted the width of a paragraph to make it less stretched out horizontally and more compact. However, when I attempted to center align the text within the paragraph using text-align: center;, only the direction of the paragraph was centered. The chall ...

Failure to load image logo when refreshing the page

There's something peculiar happening in my App.vue. Imagine I have a route link, let's say it's localhost/tools or any similar route. The logo image will display on this route. Take a look at the image here https://i.stack.imgur.com/6HaXI.p ...

Several iFrames embedded on the website automatically adjust to the same pre-set height

Apologies if this question has already been addressed, but I am struggling to properly articulate it. Here's the issue: I have a client's holiday accommodation website that uses three embedded iFrames for a Calendar, Booking Enquiry, and floorpla ...

Is there a way to stop TD from going to the next line?

I am using Javascript to dynamically generate a table and I want it to extend beyond the boundaries of the page. When I manually create the table, it works fine and extends off the page, but once I put it into a loop, the <td> elements wrap onto a se ...

Increase in JQuery .ajax timeout not effective

My website has a process where JavaScript sends a POST request to a PHP server using the .ajax() function. The PHP server then communicates with a third-party API to perform text analysis tasks. After submitting the job, the PHP server waits for a minute b ...

When running npm install, the dist folder is not automatically generated

I found a helpful tutorial at this link for creating a Grafana plugin. However, when I tried copying the code from this link to my test server (without the dist/ folder) and ran npm install, it did not generate a new dist/ folder but created a node_module ...

Obtain specific fields from a multidimensional array object using lodash

My dilemma involves working with an object that has the following structure: var data = [ { "inputDate":"2017-11-25T00:00:00.000Z", "billingCycle":6, "total":1 },{ "inputDate":"2017-11-28T00:00:00.000Z", "bi ...

Using Laravel to connect custom fonts

After previously discussing and experimenting with linking custom font files in Laravel, I encountered an issue where the fonts were not displaying correctly on my website. Due to Laravel's router, directly linking to font files in CSS was posing a ch ...

The Toggle Functionality necessitates a double-click action

I'm currently working on implementing a menu that appears when scrolling. The menu consists of two <li> elements and has toggle functionality. Everything is functioning properly, except for the fact that the toggle requires two taps to activate ...

Remove an element from an array within an object stored in a MongoDB document

Greetings and thank you for taking the time to read my query! I am currently diving into the world of coding, and here's my first question on this platform: I have a MongoDB collection structured similarly to the example below. Each document represe ...

Does the CSS overflow property affect the borders of an element?

Consider a situation where a "div" element has a border applied to it. When the overflow rule is set to 'hidden', any content that falls directly on the border will vanish. Is there a solution for this issue? It is crucial in my case to ensure t ...

What advantages does incorporating a prefix or suffix to a key provide in React development?

Is there any advantage to adding a prefix or suffix to the key when using an index as a key in React (in cases where no other value such as an id is present)? Here's an example: const CustomComponent = () => { const uniqueId = generateUniqueId( ...

Having trouble getting Typescript code to function properly when using commonjs style require statements

I am completely new to Typescript, Node.js, and Express. Following the instructions outlined in this tutorial (https://www.digitalocean.com/community/tutorials/setting-up-a-node-project-with-typescript), I set up my project exactly as described there. The ...

Leveraging the power of beautifulsoup and selenium for web scraping on a multi-page site results in gathering a

I am in the process of scraping text from a website iteratively. Each page on this particular website follows the same html structure. I utilize selenium to go to the next page each time I add the following strings: text_i_want1, text_i_wantA, text_i_wantB ...

Transform Typescript into compiled css files without using any additional tools

Currently, I am working on a monorepo project where the main project relies on another project called components. When running the entire monorepo, the main project utilizes webpack.dev while the components project simply uses the TypeScript compiler. It l ...

Remove the 'name' attribute from the input tag within the URL

Is there a way to make the server update the URL format to localhost:3000/userinput instead of localhost:3000/?name=userinput when submitting a name? Any suggestions would be greatly appreciated. Thank you in advance. ExpressJs FILE <!DOCTYPE html> ...

Allow Vue to handle the registration of the datepicker event

Is there a way to notify Vue when the datepicker changes the selected date? new Vue({ el: '#app', data: { termin: '' }, computed: { }, methods: { } }) This is just an input field: <div id="app"> <div c ...

Is there a more effective method for positioning items in a navigation bar other than using padding-left?

Hey there, I've been working on this navigation bar for quite some time now and finally found a way to center the menu items. However, I want to make sure I'm doing it the right way. Does anyone have suggestions on how to center all the "li" elem ...

What is the process of exporting a module assigned to a variable in JavaScript?

My approach to making the require visible in <app></app> is as follows: index.html: <script> var electron = require('electron') </script> <app></app> <script src="bundle.js"></script> App.vue: ...

Python code allowing users to navigate back to the previous page while retaining elements

After my script scrapes the page, it automatically clicks a button if a new element meeting certain criteria is found. Everything works perfectly when there is only one element, but an issue arises when the button click leads to a new page opening. If ther ...