0

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.

0

3 Answers 3

4

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");
Sign up to request clarification or add additional context in comments.

Comments

4

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');

Comments

1

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('')); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.