Search code examples
javascriptinsertvariable-assignmentadsensequeryselector

Adding a value by JavaScript inside a ins tag multiple time


I have this code ~

<!-- ONE -->
    <ins class='adsbygoogle'
        style='display:block'
        data-ad-client='ca-pub-XXXXXXXXXXXXXXX'
        data-ad-format='auto'
        data-full-width-responsive='true'></ins>

<!-- TWO -->
    
    <ins class='adsbygoogle'
        style='display:block'
        data-ad-client='ca-pub-XXXXXXXXXXXXXXX'
        data-ad-format='auto'
        data-full-width-responsive='true'></ins>

(Same code, two times)

I am using this to add a value "data-ad-slot=123456789"

<script> 
var x= 123456789;
var elem = document.querySelector('.adsbygoogle');
elem.dataset.adSlot = x;
console.log(elem);
</script>

But it is working only once with the first one (<!--ONE-->). How to make it working with multiple codes?

Thank you!


Solution

  • Please try this, you will have to use querySelectorAll, which would return a list.

    <!DOCTYPE html>
    <html>
    <head>
        <title>
        </title>
    </head>
    <body>
        <!-- ONE -->
        <ins class='adsbygoogle' style='display:block' data-ad-client='ca-pub-XXXXXXXXXXXXXXX' data-ad-format='auto'
            data-full-width-responsive='true'></ins>
    
        <!-- TWO -->
        <ins class='adsbygoogle' style='display:block' data-ad-client='ca-pub-XXXXXXXXXXXXXXX' data-ad-format='auto'
            data-full-width-responsive='true'></ins>
        <script>
            window.addEventListener('load', (event) => {
                var x = 123456789;
                var elems = document.querySelectorAll('.adsbygoogle');
                elems.forEach((elem) => {
                    elem.dataset.adSlot = x;    
                    console.log(elem);
                });
            });
        </script>
    </body>
    </html>
    

    Output:

    <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-XXXXXXXXXXXXXXX" data-ad-format="auto" data-full-width-responsive="true" data-ad-slot="123456789"></ins>
    
    <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-XXXXXXXXXXXXXXX" data-ad-format="auto" data-full-width-responsive="true" data-ad-slot="123456789"></ins>