I'm experiencing issues when trying to add the user's state (geolocation) to two locations within the HTML copy of my webpage using span. I've tried three different Javascript options (see near bottom of script w/in body):
document.getElementsByClassName("state"); => no error in Console but state doesn't appear for either .state
document.querySelector("span .state"); => doesn't work & Console says:
Uncaught TypeError: Cannot set property 'innerHTML' of null
document.getElementById("state"); => works but only for the first #state since an id can be used for only one item
How can I successfully add the state to both locations?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Get User State & Display</title>
<script src="https://cdn.jsdelivr.net/npm/ip-geolocation-api-jquery-sdk@1.1.0/ipgeolocation.min.js"></script>
</head>
<body>
<p>Wondering why people in <span class="state"></span> are applying to this program?</p>
<p>If you would like to know more about stock options in <span class="state"></span>, contact our team today!</p>
<script>
_ipgeolocation.enableSessionStorage(true);
var ip = sessionStorage.getItem("ip");
var country_name = sessionStorage.getItem("country_name");
var state_prov = sessionStorage.getItem("state_prov");
if (!ip || !country_name || !state_prov) {
_ipgeolocation.makeAsyncCallsToAPI(false);
_ipgeolocation.setFields("country_name, state_prov");
_ipgeolocation.getGeolocation(handleResponse, "USER_KEY");
// USER KEY OMITTED FROM THIS EXAMPLE FOR SECURITY PURPOSES – I actually use the key in my version
}
function handleResponse(json) {
ip = json.ip;
country_name = json.country_name;
state_prov = json.state_prov;
}
var stateEl = document.getElementsByClassName("state");
// var stateEl = document.querySelector("span .state"); => doesn't work
// var stateEl = document.getElementById("state"); => works but only for the first #state
stateEl.innerHTML = state_prov;
</script>
</body>
</html>