0

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

  1. document.getElementsByClassName("state"); => no error in Console but state doesn't appear for either .state

  2. document.querySelector("span .state"); => doesn't work & Console says:

    Uncaught TypeError: Cannot set property 'innerHTML' of null
    
  3. 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>
mash12
  • 1
  • 3
  • 2
    `getElementsByClassName` returns potentially multiple elements, so the result is an array like element. Not a single element, that has an `innerHTML` property on it. – Taplar Aug 07 '20 at 18:06
  • Your `querySelector` case is just a typo, there shouldn't be a space there (also, it will only apply to the first instance, you want to use `querySelectorAll` and see the duplicate for how to use that). – John Montgomery Aug 07 '20 at 18:10
  • Thank you @JohnMontgomery I was able to solve the problem by ending the script with: document.querySelectorAll("span.state").forEach(function(stateEl) { stateEl.innerHTML = state_prov; }); – mash12 Aug 07 '20 at 19:15

0 Answers0