0

I'm publishing multiple pages on WordPress with same contents but city names on titles and contents must be replaced with the current page city like New York, Los Angeles, Sacramento and so on. How do I do this on Javascript

    <script>
        function replaceText() {      
        //on page load, replace #cityName with current city name
        var cityName = document.getElementById("cityName");
        cityName.innerHTML = "New York";
        replaceText();
    
    }
    </script>
    
         <div class="container">
            <div class="row">
                <h1>Our Mental Health Services in <span id="cityName">Benton</span>, KY</h1>
                <h2>Online Counseling and Psychiatry Services in <span 
 id="cityName">Benton</span>, KY</h2>
                
            </div>
        </div>

Sanawman
  • 7
  • 4
  • 1) `replaceText()` needs to be _outside_ of the function it's calling. 2) Make sure your script is after the HTML just before the `

    ` tag.

    – Andy Jun 30 '22 at 08:21
  • lots of confusion in your question. The current city where is coming from? the span is addressed by id so I guess there's only one of those element (to change) in your page. And do you mean you are supposed to change that value when the page loads? there are other events triggering the change? and again, where is the "current city" coming from? – Diego D Jun 30 '22 at 08:22
  • Just call the function outside of itself. – aca Jun 30 '22 at 08:22
  • if you want to solve the issue just using that code like it was already correct ... you shouldn't just call the function but wait for the load event... `document.addEventListener('DOMContentLoaded', function(){ replaceText(); })` – Diego D Jun 30 '22 at 08:24
  • Wow man. Thanks. Foolish me putting the call outside of the function and script outside of the body tag... Thanks!!!!! – Sanawman Jun 30 '22 at 09:02

1 Answers1

0

First, you have two elements with the same ID. By calling getElementById, Javascript will find the first one, and do what you wish with it.

Second, you were calling the function inside her self, so she could never actually be executed.

Lastly, we don't have the whole HTML code, so I'm not sure where where you calling the script, so I've put it as an external file in the snippet.

function replaceText() {      
        //on page load, replace #cityName with current city name
        var cityName = document.getElementById("cityName");
        var cityNameH2= document.getElementById("cityNameH2");
        cityNameH2.innerHTML = cityName.innerHTML = "New York";           
    }
     replaceText();
   
         <div class="container">
            <div class="row">
                <h1>Our Mental Health Services in <span id="cityName">Benton</span>, KY</h1>
                <h2>Online Counseling and Psychiatry Services in <span 
 id="cityNameH2">Benton</span>, KY</h2>
                
            </div>
        </div>
aca
  • 1,071
  • 5
  • 15