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>
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>