Jacob
Jacob

Reputation: 4031

Adding to innerHTML correct syntax

What is the correct syntax if I want to add content to an element using innerHTML. Below is my non working example:

   openNewWindow: function(content) {
popupWin = window.open(content,
    'open_window',
    'menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480, left=0, top=0')
},

for (var index in mv.exifImages) {
        ele.innerHTML += "<p onclick = openNewWindow(mv.exifImages[index]> image" + index + "</p>";
    }

Upvotes: 0

Views: 265

Answers (3)

Frances McMullin
Frances McMullin

Reputation: 5706

innerHTML is not your problem, your code is lacking context.

    openNewWindow: function(content) {
        popupWin = window.open(content,
            'open_window',
            'menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480, left=0, top=0');
        // call to window.open ended here
    },
    // judging by the definition of openNewWindow and the comma above,
    // we are inside an object definition!

    // you cannot embed a for loop inside an object definition!!!
    for (var index in mv.exifImages) {
        ele.innerHTML += "<p onclick = openNewWindow(mv.exifImages[index]> image" + index + "</p>";
    }

Put your for loop somewhere sensible, like inside a function, or actually show us the error you are getting.

Upvotes: 0

999k
999k

Reputation: 6565

i think it is. variable index has local scope

for (var index in mv.exifImages) {
        ele.innerHTML += "<p onclick = 'openNewWindow(\"" + mv.exifImages[index] + "\")'> image" + index + "</p>";
    }

Upvotes: 1

Salvatorelab
Salvatorelab

Reputation: 11873

Use appendChild:

var myelement = document.getElementById("myelement");
myelement.appendChild( document.createTextNode("Example text inside myelemen") );

This is better that overwriting innerHTML, as it preserves onclick events for example:
Is it possible to append to innerHTML without destroying descendants' event listeners?

Upvotes: 0

Related Questions