For a class assignment I need to position an image of a square, either left, right or center depending on which corresponding radio button I click.
I wish to keep as much styling out of JavaScript as I can. However this is proving a problem as I am unable to access what I want. Example:
This is one of the radio buttons:
<input type="radio" id="center" name="position" onclick=moveShape() value="center">center
The shape itself:
<span id="square">
</span>
its JavaScript:
function moveShape() {
var center = document.getElementById("center");
var shape = document.getElementById("square");
if(center.checked){
// access CSS here
}
and then I want to access styling, such as:
#somenewid {
width: 10px;
height: 10px;
background-color: red;
display: inline-block;
// code to center it
}
I have tried setting a new id. Such as shape.id = "cent"; which works once, but if I then click another radio button and come back to the center button, it tells me the ID is null.
I do not, and cannot, be given the answer to the assignment but I do need to know how to set my HTML/JavaScript elements such that I am able to access CSS styling.
window.getComputedStyle(element)in your case that would bewindow.getComputedStyle(shape)more information on mdnstyleattribute to the elementshape.setAttribute("style", "left: 10px; top: 20px");styleproperty directly:shape.style.left = '10px';getAttributebut upon further research it seems the only downside of setting the style this way is that it'll overwrite any inline styles you set in the HTML. It should perhaps be noted though that you can still set multiple styles viaObject.assign(shape.style, {left:'10px',top:'20px'})but I guess it doesn't matter how you do it.