Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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 literally adds "<div ..." on my page.

Can anyone help me please? Sorry for the bad spelling and grammar.

like image 951
Onovar Avatar asked Jan 05 '23 10:01

Onovar


1 Answers

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");
el.appendChild(document.createTextNode("Put yout HTML"));
document.getElementById(name+'id').appendChild(el);
like image 180
Markus Zeller Avatar answered Jan 06 '23 23:01

Markus Zeller