Onovar Onovar -4 years ago 128
HTML Question

.append() adds html as text

I'm using javascript to add html to my 's.
I made a loop that goes around all projects there are. There are multiple projects and in every project there are multiple pictures.

The first part creates the first projecttitle within a div that gets an id(the projectname) and the first pictures.

$( ".projectbeeldcontainer" ).append(


'</div>'+
'<h1 class="projecttitel" id="'+name+'">'+name+'</h1>'+
'<div class="row dashboardrow" id="'+name+'id">'+
'<div class="col-sm-2">'+
'<div class="thumbnail">'+
'<a href="/w3images/lights.jpg">'+
'<img src="projectbeelden/'+name+'/'+decodeURI(image)+'" class="img-rounded">'+
'</a>'+
'<div class="caption tags">'+
'<p>titel van project</p>'+
'</div>'+
'</div>'+
'</div>';

);


After this, the script will check if the projectname of the next image allready exists. If it does exist (because we added it with the code above), then it will insert a new div inside of the project div we created:

document.getElementById(name+'id').append(


'<div class="col-sm-2">'+
'<div class="thumbnail">'+
'<a href="/w3images/lights.jpg">'+
'<img src="projectbeelden/'+name+'/'+decodeURI(image)+'" class="img-rounded">'+
'</a>'+
'<div class="caption tags">'+
'<p>titel van project</p>'+
'</div>'+
'</div>'+
'</div>'




);


The problem i have now is that the first line of code successfull creates the div's and the image. The second code works for 98%.

It does recognise the div with the id and puts the content in it. But the problem is that it adds quotes before my first line and after. So it looks like it thinks it's a string and not html.

so it litterly adds "

can anyone help me please? Sorry for the bad spelling and grammer.

Answer Source

Use innerHTML instead of append.

document.getElementById(name+'id').innerHTML += "<div> put your html </div>";

Append adds a textNode. Better way is something like this by generating it and inserting into the DOM:

var el = document.createElement("div"); document.getElementById(name+'id').appendChild(el);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download