Harsha Venkataramu
Harsha Venkataramu

Reputation: 2904

Add a class to dynamically created list element

I have the following code which takes an input from an xml and creates an unordered list.

$(function() {
            var map = function() {
                    if ($(this).is("parent")) {
                        var children = $(this).children().map(map).get().join('');
                        $(this).children().remove();
                        var result = "<li class='BGOfDiv'>" + $(this).text();
                        return result + "<ul>" + children + "</ul></li>";
                    }
                    if ($(this).is("Children")) {
                        return "<li class='BGOfDiv'>" + $(this).text() + "</li>";
                    }
                };

                $.get("test.xml", function(data) {
                    var result = $(data).map(map);
                    $("#org").html(result[0]);
                    $("#org").jOrgChart({
                            chartElement : '#chart',
                            dragAndDrop  : false
                        });
                        dragNodes();
                }, "html");

            }); 

Currently,my xml looks like this

<?xml version="1.0" encoding="utf-8"?>
<Parent>Director
    <Children>Exe Director1</Children>
    <Children>Exe Director2</Children>
    <Parent>Exe Director3
        <Children>Sub Director 1</Children>
        <Children>Sub Director 2</Children>
        <Parent>Sub Director 3
            <Children>Cameraman 1</Children>
            <Children>Cameraman 2</Children>
        </Parent>
    </Parent>    
</Parent>

However,the xml will be made to hold the paths of certain images which I need to apply as the background-image for each node.That is my xml will look like

<?xml version="1.0" encoding="utf-8"?>
<Parent>../images/1.jpg
    <Children>../images/2.jpg</Children>
    <Children>../images/3.jpg</Children>
    <Parent>../images/4.jpg
        <Children>../images/5.jpg</Children>
        <Children>../images/6.jpg</Children>
        <Parent>../images/7.jpg
            <Children>../images/8.jpg</Children>
            <Children>../images/9.jpg</Children>
        </Parent>
    </Parent>    
</Parent>

I understand that I will need to use the .css property of jquery and set the background-image when I create the new <li> element but I am not able to figure out how that can be done.

Thanks for looking.Any help will be appreciated.

Upvotes: 0

Views: 638

Answers (1)

VVV
VVV

Reputation: 7593

If $(this).text() returns the url of the file, you could simply add the style in the <li> element

"<li class='class' style='background-image: url(" + $(this).text() + ");'>...</li>"

Of course you would probably need to setup other CSS like background-position, background-repeat, etc. Or use the short version of the css like

"<li class='class' style='background: url(" + $(this).text() + ") no-repeat 0 0;'>...</li>"

Upvotes: 1

Related Questions