Julian Coltea
Julian Coltea

Reputation: 3609

css not being applied to html elements created with jQuery .append()

So I know this is probably horrible programming practice, but I'm in a bit of a time crunch, and basically I have a tag within my code, and upon clicking a button on the screen, I'm trying to append a bunch of code inside that div. However, I've noticed two things. One, my other javascript crashes UNLESS the appended code is all on one line, and two, my css style sheets aren't being applied to the code even though I've assigned classes. Here's the relevant code:

            $("#results").append("<ul class='sdt_menu'>");
            for(i=0; i < progression[max].length;i++)
            {
                $("#results").append(
            "<li><a href='#'><img src='images/youAreHere.jpg' alt=''/><span class='sdt_active'></span><span class='sdt_wrap'><span class='sdt_link'>"+progression[max][i]+"</span><span class='sdt_descr'>hover to view description</span></span></a><div class='sdt_box'>"+jobs[progression[max][i]]['description']+"</div></li>");
            }

            $("#results").append("</ul>");

Any help demystifying this would be greatly appreciated.

Upvotes: 0

Views: 11420

Answers (3)

Alnitak
Alnitak

Reputation: 340055

In your current code, as soon as you add the <ul> it gets automatically closed by the browser (since it's impossible to have unclosed tags in the DOM) and then your <li> are being added to #results too. Or at least, they would be, if it were legal to have an <li> be a child of a <div>.

Instead, you need to append your <li> elements to the <ul>, not to #results:

var $ul = $("<ul class='sdt_menu'>");
for (i = 0; i < progression[max].length; i++) {
    $ul.append(...);
}
$ul.appendTo('#results');

Upvotes: 4

Hiral Vadodaria
Hiral Vadodaria

Reputation: 19250

Try this:

 var tag = [];
 var ic=0;
 tag[++ic] = '<ul class="sdt_menu">';
 for(var i = 0; i < progression[max].length; i++) {
     tag += '...all of your other list items';
 }
 tag[++ic] = "</ul>";

 $("#results").append(tag.join('')); 

Upvotes: 1

Jim H.
Jim H.

Reputation: 5579

When you append, you should be appending an entire, complete, closed set of tags. It doesn't work like a stringbuilder. Try instead something like:

var tag = '<ul class="sdt_menu">';
for(var i = 0; i < progression[max].length; i++) {
    tag += '...all of your other list items';
tag += "</ul>";

$(tag).appendTo("#results");

Upvotes: 4

Related Questions