tags:

views:

33

answers:

3

I am trying to programatically add a DIV with the class of error_icon to the page using jQuery. This is the HTML:

<div id="error_icon_holder"></div>

When they're added, the markup should resemble:

<div id="error_icon_holder">
    <div class="error_icon"></div>
</div>

I tried using .addClass, but that resulted in:

<div id="error_icon_holder" class="error_icon"></div>

And I also tried .after which also didn't work. Can someone let me know how to do this? Thanks.

+4  A: 

You want .append()

$('#error_icon_holder').append('<div class="error_icon"></div>');

You could also flip it around, and use .appendTo().

$('<div class="error_icon"></div>').appendTo('#error_icon_holder');

Or since error_icon_holder appears to be empty, you could use .html(). (This would normally overwrite any existing content.)

$('#error_icon_holder').html('<div class="error_icon"></div>');
patrick dw
A: 

You can use this so that you have access to the error_icon div after it is created:

var errorIcon = $('<div/>');
errorIcon.addClass('error_icon');
$('#error_icon_holder').append(errorIcon);
s_hewitt
A: 

To expand on that patrick offered, .append() will preserve any existing content within the error_icon_holder div. If you would like to replace the contents entirely, use .html().

If you don't want to include the error_icon class with the inner div creation statement you'll need two separate statements, one to create the inner div within the DOM tree and another to add the class to the newly created element.