I'm trying to create a script on a website that takes the user's location and displays the results. I have a problem with the setting and styles. How can i edit style or how can i edit the code so that it can work with css styles in <div>
my code:
<pre></pre>
<script>
const address = document.querySelector("pre");
function onError() {
address.innerText = "";
}
async function onSuccess(position) {
const geocode = await fetch(`/${position.coords.latitude},${position.coords.longitude}?json=1`);
const geoResponse = await geocode.json();
address.innerText = `${geoResponse.country}, ${geoResponse.city}, ${geoResponse.postal}, ${geoResponse.staddress}`;
}
if (!navigator.geolocation) {
onError();
} else {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
</script>
I'm trying to create a script on a website that takes the user's location and displays the results. I have a problem with the setting and styles. How can i edit style or how can i edit the code so that it can work with css styles in <div>
my code:
<pre></pre>
<script>
const address = document.querySelector("pre");
function onError() {
address.innerText = "";
}
async function onSuccess(position) {
const geocode = await fetch(`https://geocode.xyz/${position.coords.latitude},${position.coords.longitude}?json=1`);
const geoResponse = await geocode.json();
address.innerText = `${geoResponse.country}, ${geoResponse.city}, ${geoResponse.postal}, ${geoResponse.staddress}`;
}
if (!navigator.geolocation) {
onError();
} else {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
</script>
Share
Improve this question
asked Dec 3, 2020 at 16:35
newstudentnewstudent
211 silver badge2 bronze badges
1
- You can review the javascript style – sercan Commented Dec 3, 2020 at 16:40
2 Answers
Reset to default 2I've created a snippet with your code. In this case, we are targeting a pre
element.
const address = document.querySelector("pre");
address.style.backgroundColor = "blue";
address.style.color = "white";
address.style.fontWeight = "900";
pre {
height: 500px;
width: 500px;
}
<pre>This is a pre element</pre>
However, if you wanted to target a class, you would do this:
<div class="pre"></div>
const address = document.querySelector(".pre");
For id you would do this:
<div id="pre"></div>
const address = document.querySelector("#pre");
When you use id or class you can still target your styles the same way:
address.style.backgroundColor = "blue";
address.style.color = "white";
address.style.fontWeight = "900";
More info here.
document.getElementById(id).style.property = new style
in your case:
const address = document.querySelector("pre");
address.style.color= "red"