rism
rism

Reputation: 12132

jQuery append doesn't work when using a class name as part of the element definition

When trying to append one div to another Im finding that this doesn't work:

 var htmlCell = jQuery('<div id="ddd"></div>').attr({ 'className': "basecell" }).css({ 'top': 165 + 'px' }).css({ 'left': 335 + 'px' }).css({ 'background-color': '#ffffff' });
 $("#dtest").append(htmlCell);

but this does:

 var htmlCell = jQuery('<div id="ddd"></div>').css({ 'height': 165 + 'px' }).css({ 'width': 165 + 'px' }).css({ 'position': 'absolute' }).css({ 'top': 165 + 'px' }).css({ 'left': 335 + 'px' }).css({ 'background-color': '#ffffff' });
 $("#dtest").append(htmlCell);

With the CSS below:

#dtest
{    
    position: relative;
    top: 0px;
    left: 50px;
    height: 469px;
    width: 685px;
    z-index: 86;
    background-color: #000000;
}
.basecell
{
    position: absolute;
    width: 116px;
    height: 116px;
    background-color: #ffffff;

}

In both cases the children().length of #dtest is 1 but in the statement that uses a class it is not visible. Any ideas?

Upvotes: 1

Views: 2126

Answers (3)

Exel Gamboa
Exel Gamboa

Reputation: 946

I will share this in case it happen to any of you that develop for both desktop and mobile and use Bootstrap to hide and show some elements.

When using append or any function that modifies the HTML, make sure you are manipulating the element that is visible to you at the moment.

For me, append was not working and I had the browser window at 300 pixels width. After 4 hours of research looking for an answer of why the append didn't work, I look at my HTML, saw the two tables with the 'visible-xs' and 'hidden-xs' respectively and I wonder for a moment. When I maximize the browser ... voila! There was the list with all the appends as expected. I was editing the table with the 'hidden-xs' but watching the table with the 'visible-xs' class.

Don't be like me! :)

Upvotes: 0

Seyeong Jeong
Seyeong Jeong

Reputation: 11028

var htmlCell = jQuery('<div id="ddd"></div>').addClass("basecell").css({ 'top': 165 + 'px' }).css({ 'left': 335 + 'px' }).css({ 'background-color': '#ffffff' });
$("#dtest").append(htmlCell);

You can also do:

$('<div id="ddd">').addClass("basecell").css({ 'top': 165 + 'px', 'left': 335 + 'px', 'background-color': '#ffffff }).appendTo($("#dtest"));

There is no attribute called className. If you want to set class name to an element using jQuery, you have to use $(elem).addClass('classname') method. Conversely, you can remove a class using $(elem).removeClass('classname'). To remove all classes, use $(elem).removeClass().

Upvotes: 3

Tetaxa
Tetaxa

Reputation: 4403

className isn't the attribute you're looking for. Move along. It should be class or use jQuery's addClass method like Calvin suggested.

Upvotes: 0

Related Questions