Jeff Peak Jeff Peak - 6 months ago 20
Javascript Question

Javascript create elements in two places

How would I need to write this to have the elements created in two places?

Here is my code.

I have tried using

document.getElementsByName
and
document.getElementsByClassName
and neither of them work.

HTML

<p style="display:block;" class="coords"></p>


Javascript

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}

function showPosition(position, coords)
{
var places = document.getElementsByClassName(coords);
for (var i = 0; i < places.length; i++)
{
places[i].innerHTML = "<input type='text' name='lat' id='lat' value='" + position.coords.latitude + "'>" +
"<input type='text' name='lon' id='lon' value='" + position.coords.longitude + "'>";
}
}

Answer

After calling getElementsByClassName you must use a loop to update each of them.

function showPosition(position) {
    var places = document.getElementsByClassName("coords");
    for (var i = 0; i < places.length; i++) {
        places[i].innerHTML="<input type='text' name='lat' id='lat' value='" + position.coords.latitude + "'>" +
                            "<input type='text' name='lon' id='lon' value='" + position.coords.longitude + "'>";
    }
}
Comments