Reputation: 302
I am trying to dynamically create HTML code with JavaScript using JS variables in the HTML tags. The code is then inserted into my HTML file via .innerHTML
.
What isn't working (I didn't expect it to work really, but I'm not sure how to force it to work) is setting the id
and margin-right
attributes to JS variables (using dynamicID
and equalMargin
respectively).
var numberOfImages = 7
var equalMargin = 1; //(divElement.clientWidth - equalWidth*7) / 6;
var dynamicCode = "";
var dynamicID = "";
var i;
for(i = 0; i < numberOfImages - 1; i++)
{
dynamicID = "navDot" + i + "";
console.log(dynamicID);
dynamicCode = dynamicCode + '<img src = "https://dl.dropboxusercontent.com/s/mvj24qzluobu098/seekDotEmpty.png?dl=0" alt = "emptyDot" id = dynamicID style = "max-height: 100%; margin-right = equalMargin;">';
}
Upvotes: 1
Views: 70
Reputation: 38121
Just end the string, add the variable, and reopen the string.
Also, there are no spaces between attributes, the equals (=
) sign and their values.
var numberOfImages = 7
var equalMargin = 1; //(divElement.clientWidth - equalWidth*7) / 6;
var dynamicCode = "";
var dynamicID = "";
var i;
for(i = 0; i < numberOfImages - 1; i++)
{
dynamicID = "navDot" + i + "";
console.log(dynamicID);
dynamicCode = dynamicCode + '<img src="https://dl.dropboxusercontent.com/s/mvj24qzluobu098/seekDotEmpty.png?dl=0" alt="emptyDot" id="' + dynamicID + '" style="max-height: 100%; margin-right: ' + equalMargin + ';">';
}
Upvotes: 1