I have a code here that i was supposed to make to change a style property, managed to make it work, but had to look up at the proper way to place the ', the " and the + .
document.getElementById('image').style.backgroundImage="url('" + element.src + "')";
I have no issue understanding how structurally this works, my only question resides on why of the extra ', extra " and extra + inside where you call for the element.src.
originally i did something like this, and it obviously didnt work, why did those ('" + and + "') make the code work...
any help is appreciated
cheers
document.getElementById('image').style.backgroundImage="url(' element.src ')";
Let's analyze everything from your first code segment and that should give you a better understanding:
document.getElementById('image').style.backgroundImage="url('" + element.src + "')";
document
is a variable
getElementById
is a function, with the string 'image'
being a parameter for that function.
style
is a property
backgroundImage
is a property which must be and must take a string
"url('"
is a string
element
is a variable, an object in this case, with src
being one of its properties.
"')"
is a string
The +
signs are used to concatenate the string formed from "url('"
, element.src and "')". In short you are saying, "make a string from "url('"
, element.src
and "')"
and assign that string to the property backgroundImage
.
Whereas in this:
document.getElementById('image').style.backgroundImage="url(' element.src ')";
The browser has no idea that element.src
is a variable and not part of the string, since you enclosed it int double quotes, signaling that everything between the quotes is a string.