Jquery Append not working in the expected order

Happy New Year. I am trying to create pagination links. So basically my code is big, so I created below code for easy understanding.

<div id = "test"></div>

func1();

function func1() {
    $("#test").append("<nav><ul class='pagination pagination-lg'>");
    func3();
    $("#test").append("</ul></nav>");
}

function func2() {

$("#test").append("<li>data</li>"); 
}

function func3() {
func2();
}

      

I expect the result to be like

<nav><ul class="pagination pagination-lg"><li>data</li></ul></nav>

      

But the conclusion

<nav><ul class="pagination pagination-lg"></ul></nav><li>data</li>

      

Why is this happening? Although I am calling the function before adding</ul></li>

Ps Fiddle http://jsfiddle.net/s6d5wytf/

+3


source to share


1 answer


When you add invalid HTML, the browser will do its best to turn it into well-formed HTML when you do:

    $("#test").append("<nav><ul class='pagination pagination-lg'>");

      

The browser sees that it has an open tag <ul>

without </ul>

, and suppose what you did with it - especially since a little known fact - the tags are </ul>

implicit and can be inferred by the browser.

So - what are you conceptually adding the first time:



    $("#test").append("<nav><ul class='pagination pagination-lg'></ul></nav>");

      

What you want to do is either use a temporary element that you create and attach or chain strings. Here is an example of the first approach

function func1() {
    var menu = $("<nav></nav>"); // create but not add anywhere
    menu.append("<ul class='pagination pagination-lg'></ul"); // add ul
    func3(menu);
    $("#test").append(menu);
}

function func2(menu) {
    menu.find("ul").append("<li>data</li>"); 
}

      

It also has the added benefit of only asking for the actual document once, which is faster, although if you only do this 3 times, it's negligible.

+5


source







All Articles