StevenDStanton StevenDStanton - 5 months ago 12
Javascript Question

Jquery insertBefore inserting text not HTML

The examples at http://api.jquery.com/insertbefore/ show insertBefore inserting new HTML into the DOM

My HTML is structured as follows:

<div class="left line">
<div class="steps" id="step1"></div>
</div>
<div class="left line">
<div class="steps" id="step2"></div>
</div>


I call this after the document is ready (Note I attempted to wrap the text in both "" and '' and got the same results. The code is running in a for loop and is inserting in the correct position.

if (opts[i].payments1) {
console.log("P1")
$( "< div class = 'payment1'> < /div>" ).insertBefore( "#step" + i );

}


when I run the code I get this

<div class="left line">
&lt; div class = 'payment1'&gt; &lt; /div&gt;
<div class="steps" id="step1" style="background-color: blue;"></div>
</div>


So when viewing the page I get

< div class = 'payment1'> < /div>

instead of the formatting of the div

Answer

I assume jQuery doesn't like to way how you wrote <div..... Try

 $( "<div class='payment1'> </div>" ).insertBefore( $("#step" + i) );

get rid of spaces.

Comments