I have a simple header that I would like to populate with a City Name if it matches an ID. I am currently using replaceWith and it only seems to work on the first time. Not sure why?
Here is the function:
function toggleDetails() {
$(".pin").click(function() {
var cityName = $(this).attr('id');
$(".city-details").toggle();
if (cityName === 'Miami') {
$('h3#cityName').replaceWith("Miami");
}
else if(cityName === 'Philadelphia') {
$('h3#cityName').replaceWith("Philadelphia");
}
else if (cityName === 'Chicago') {
$('h3#cityName').replaceWith("Chicago");
}
else if (cityName === 'Los-Angeles') {
$('h3#cityName').replaceWith("Los Angeles");
}
else if (cityName === 'Houston') {
$('h3#cityName').replaceWith("Houston");
}
else if (cityName === 'San-Diego'){
$('h3#cityName').replaceWith("San Diego");
}
else if (cityName === 'Atlanta') {
$('h3#cityName').replaceWith("Atlanta");
}
console.log(cityName);
});
}
HTML:
<p class="pin totally newyork" id="NewYork">
New York
</p>
<p class="pin barely boston" id="Boston">
Boston
</p>
<p class="pin fairly philadelphia" id="Philadelphia">
Philadelphia
</p>
<p class="pin barely chicago" id="Chicago">
Chicago
</p>
<p class="pin barely la" id="Los-Angeles">
Los Angeles
</p>
<p class="pin fairly houston" id="Houston">
Houston
</p>
replaceWithwill remove the element and replace it with the given text, hence there’s no longer an element to be replaced after the first time. Try with.textor.html. Also your code seems a little redundant as well.Fiddle