Skip to content

How to make this code work with .each function?

I have the following piece of code in a script tag that I need to get working for all #tel ID elements on the page. I can only get it to work for the first #tel element. I’ve been trying to use .each function – but no luck…

The reason being is that I can’t seem to get the ACF repeater URL to suit my needs here. The Advanced section of the dynamic content link part is not displaying. So I am trying to make a hack in an HTML widget for this. But I need it to work for all buttons with button ID #tel.

Here’s the code:

var link = document.getElementById('tel');
var href = link.getAttribute('href');

link.setAttribute('href', href.replace('http://', 'tel:'));
<div class="elementor-button-wrapper">
    <a href="http://44400907" class="elementor-button-link elementor-button elementor-size-xs" role="button" id="tel">
        <span class="elementor-button-content-wrapper">
            <span class="elementor-button-text elementor-inline-editing" data-elementor-setting-key="text" data-elementor-inline-editing-toolbar="none">
                44 40 09 07
            </span>
        </span>
    </a>
</div>

Answer

In HTML/javascript element IDs must be unique. So in your case you can use class for that:

var links = document.querySelectorAll('.tel');
for(let i = 0; i < links.length; i++)
{
  let link = links[i];
  var href = link.getAttribute('href');

  link.setAttribute('href', href.replace('http://', 'tel:'));
}
<div class="elementor-button-wrapper">
            <a href="http://44400907" class="elementor-button-link elementor-button elementor-size-xs tel" role="button">
                        <span class="elementor-button-content-wrapper">
                        <span class="elementor-button-text elementor-inline-editing" data-elementor-setting-key="text" data-elementor-inline-editing-toolbar="none">44 40 09 07</span>
                </span>
            </a>
    </div>
    
<div class="elementor-button-wrapper">
            <a href="http://44400908" class="elementor-button-link elementor-button elementor-size-xs tel" role="button">
                        <span class="elementor-button-content-wrapper">
                        <span class="elementor-button-text elementor-inline-editing" data-elementor-setting-key="text" data-elementor-inline-editing-toolbar="none">44 40 09 08</span>
                </span>
            </a>
    </div>

<div class="elementor-button-wrapper">
            <a href="http://44400909" class="elementor-button-link elementor-button elementor-size-xs tel" role="button">
                        <span class="elementor-button-content-wrapper">
                        <span class="elementor-button-text elementor-inline-editing" data-elementor-setting-key="text" data-elementor-inline-editing-toolbar="none">44 40 09 09</span>
                </span>
            </a>
    </div>