0

I'm dynamically generating a list from a MongoDB database using getJSON().

The HTML being generated is correct and the related CSS styles are also correct.

The <li>'s should have images as backgrounds, but they aren't being applied.

In Firebug, I hover over the image background URL for each <li> and the image is previewed so I can tell the path is correct, they are just not being displayed.

The solutions I have come across involve using listview('refresh') but that seems to be a jQuery Mobile solution and I am just using standard jQuery.

Another solution I have seen is to use addClass() to an element after the function has run, but the element already has the correct class applied in the HTML, the style is just not being displayed.

Is there a 'standard' way of re-applying CSS after a function has run, or another approach to ensure that CSS is applied to a dynamically generated list?

HTML

<ul class="my_ul_class"></ul>

jQuery (external js file)

$(document).ready(function() {
    loadListItems();
});

function loadListItems() {
    var href= "/url";
    $.getJSON("/path_to_python_script", {cid: href, format: 'json'}, function(results){
        $.each(results.my_key, function(k,v) {
            $("ul.my_ul_class").append("<li data-thing1=\"" + v + "\" class=\"prefix_" + v + "\"><ul class=\"nested\"><li class=\"hidden_li\"><p class=\"my_p_class\">text</p></li></ul></li>");
        });
    })
}

Generated HTML

<li class="prefix_1" data-thing1="1"><ul class="nested"><li class="hidden_li"><p class="my_p_class">text</p></li></ul></li>
SnoringFrog
  • 1,479
  • 1
  • 16
  • 30
user1063287
  • 10,265
  • 25
  • 122
  • 218
  • What I would do is create a .css file generated by the back-end and returning the path to the file in your JSON callback. Then append that file to the head-tag using jQuery. – Kevin Dec 30 '13 at 08:19
  • apply in css file this way: `ul.my_ul_class li{ color: blue;}` this will be applied to every list items. – Jai Dec 30 '13 at 08:21
  • Is it really working with li items added manually and only not working with dynamic generated items? – Mujtaba Haider Dec 30 '13 at 08:22
  • Css classes apply to both newly create and initial dom elements. You're searching on the wrong path. – Florian F. Dec 30 '13 at 08:26
  • @MujtabaHaider Good troubleshooting suggestion. Yes, it is working when `
  • `'s are hardcoded. To test, I copied the generated `
  • `'s to the HTML file and removed the function and they displayed correctly.
  • – user1063287 Dec 30 '13 at 08:31
  • @user1063287 please add a jsfiddle. That's the best way to understand your code. – Niks Dec 30 '13 at 08:40