views:

25

answers:

2

Right i'm trying to insert some basic html before a div like this

<script>$("div#header").before("<div class="test">test</div>");</script>

However nothing appears, but when i try the jquery example

<script>$("p").before("<b>Hello</b>");</script>

it works, what i'm i doing wrong?

Thanks

+3  A: 

You need to escape the quotation marks in the string literal like this:

"<div class=\"test\">test</div>"

Also, all DOM manipulation needs to occur after the browser has finished parsing the HTML document (also called "preparing the DOM"). The browser fires the "load" event for document when the "DOM is ready".

In jQuery, you write a callback for "DOM ready" like:

$(document).ready(function() {
    $("div#header").before("<div class=\"test\">test</div>");
});
Daniel Trebbien
+1  A: 

If you're using exactly that code, you should be getting a JavaScript error due to the unterminated string. Try this:

$('#header').before('<div class="test">test</div>');
Dave Ward