Dana Garcia
Dana Garcia

Reputation: 21

ASP.NET Generated Output Not Effected By JQuery/Javascript

I have the below code that is dynamically generates a directory tree in html list format. When I try to manipulate the list items with javascript to add a '+' to the end of the item, it doesn't work. I know the jquery is correct, I have used it on another page on the same server. Is jquery not able to manipulate data that is dynamically generated server side with asp.net?

<script langauge="C#" runat="server">
    string output;
    protected void Page_Load(object sender, EventArgs e) {
        getDirectoryTree(Request.QueryString["path"]);
        itemWrapper.InnerHtml = output;
    }

    private void getDirectoryTree(string dirPath) {
        try {
            System.IO.DirectoryInfo rootDirectory = new System.IO.DirectoryInfo(dirPath);
            foreach (System.IO.DirectoryInfo subDirectory in rootDirectory.GetDirectories()) {
                output = output + "<ul><li>" + subDirectory.Name + "</li>";
                getDirectoryTree(subDirectory.FullName);
                if (subDirectory.GetFiles().Length != 0) {
                    output = output + "<ul>";
                    foreach (System.IO.FileInfo file in subDirectory.GetFiles()) {
                        output = output + "<li><a href='" + file.FullName + "'>" + file.Name + "</a></li>";
                    }
                }
                output = output + "</ul>";
            }
        } catch (System.UnauthroizedAccessException) {
            //This throws when we don't have access, do nothing and move one.
        }
    }
</script>

I then try to manipulate the output with the following:

<script langauge="javascript">
    $('li > ul').not('li > ul > li > ul').prev().append('+');
</script>

Just an FYI the code for the div is below:

<div id="itemWrapper" runat="server">
</div>

Upvotes: 0

Views: 120

Answers (2)

Becuzz
Becuzz

Reputation: 6866

It looks like you have a couple of problems here. First you should put your jQuery code inside of $(document).ready. That ensures that the DOM has fully loaded before you try to mess with it. Secondly, your selector is looking for ul elements that are direct children of li elements. Your code does not generate any such HTML. You have li's inside of ul's but not the other way around. Also, if your directory has files in it, you are going to leave some ul elements unclosed which will mess up your HTML and Javascript.

Upvotes: 0

Felipe Miosso
Felipe Miosso

Reputation: 7339

Have you tried execute your JS after the page loads? Something like this ...

$(function(){ 
    $('li > ul').not('li > ul > li > ul').prev().append('+');
});

Upvotes: 1

Related Questions