to0ns88
to0ns88

Reputation: 41

Add <li> to each element in jquery variable (before adding to UL)

What i'm trying to do

  1. Bring in a selection of html elements from an external html (on the same domain) into a variable in jquery (working)
  2. for each of the element items, wrap them (not working)
  3. prepend that variable to a ul in my page (working)

I have the following code that at this point, works, however it just dumps the elements (el) onto the page in one large list item, not each line on its own

$(document).ready(function() {
var $div = $('<li>');

$div.load('pages.html .el', function(){
    $("#my-menu ul.toc").prepend($div);
});
});

I've tried a weird selection of wrapall, etc, but can't seem to crack this.

Would really appreciate any help. Thanks

Upvotes: 1

Views: 2154

Answers (3)

levelnis
levelnis

Reputation: 7705

You need to loop through the elements once they've been loaded from the external html. Something like this (untested code) might work:

$(document).ready(function() {
    var $div = $('<div></div>');
    var $ul = $('#my-menu ul.toc');

    $div.load('pages.html .el', function(){
        $div.children().each(function() {
            $ul.prepend($('<li>' + $(this) + '</li>'));
        });
    });
});

If the prepend to the ul doesn't work in one line, it might work if you separate it:

var $li = $('<li></li>');
$li.html(this);
$ul.prepend($li);

Upvotes: 1

Repo
Repo

Reputation: 1745

Try and load the html in a hidden div..

$("<div id='pagesHtml' style='display: none;'></div>").appendTo("body");
$("#pagesHtml").load(pages.html);

..store the anchors in a variable..

var $anchors = $("#pagesHtml").find(".el");

..then make a LI for each anchor..

$.each($anchors, function(i, anchor){
    $("<li>" + anchor + "</li>").prependTo("#my-menu ul.toc");
});

..and then add that to your container.

If the order is wrong, then you should use ".appendTo" instead.

Happy coding =)

Upvotes: 0

latikas
latikas

Reputation: 127

I could not say anything without seeing the code, but you can try this one,

$(document).ready(function() {
var $div = $('<li>');

$div.load('pages.html .el', function(){
    $("#my-menu ul.toc").insertBefore($div);
});
});

Upvotes: 0

Related Questions