I'm trying to change the syntax in this code

I'm a beginner in Javascript. I just wonder how I can use style instead of using a new var in this code.

 var style =
"position:absolute;" +
"width:" + newObj.radius + "px;" +
"left:" + newObj.xPos + "px;" +
"top:" + newObj.yPos + "px;";
newImg.setAttribute("style", style);

I want the plus signs to be removed from the end of each line. I tried the following code, but it doesn't work.

newImg.style.position = "absolute;";
newImg.style.width= newObj.radius + "px;";
newImg.style.left = newObj.xPos + "px;";
newImg.style.top = newObj.yPos + "px;";
728x90

2 Answers I'm trying to change the syntax in this code

You question is how to set HTML element's CSS attributes using _Object_.style's properties vs. setting a style using string value

Like this:

newImg.style.position = "absolute";
newImg.style.width= newObj.radius + "px";
newImg.style.left = newObj.xPos + "px";
newImg.style.top = newObj.yPos + "px";

All of these can be found in CSS Reference documentation - look for Javascript syntax for each property

6 days ago

Try this

document.getElementById("theIdYouMadeInHTML").style.property = new style;

As shown in here: https://www.w3schools.com/js/js_htmldom_css.asp

6 days ago