Search code examples
javascriptjqueryajaxdynamicbind

Access new generated content in jQuery


In all the research I have found, they invoke binding an even to the element with .on(), but that not what I need. Here is a brief example:

<div id="myElement">
    <ul id="myUl">
        <li>content list 1</li>
        <li>content list 2</li>
    </ul>
</div>

After an ajax call, I replace the content of myElement using:

var div = $("#myElement");
div.replaceWith('<div id="myElement">
    <ul id="myUl">
        <li>new content list 1</li>
        <li>new content list 2</li>
    </ul>
</div>');

Now if I want to access the unordered list to add for example a class name: div.find("ul").addClass("myClass"); it doesn't work. Any idea how to solve this?


Solution

  • This works for me...

    • added a # to get the element using ID
    • used the ID again after replacing
    • escaped the newlines
    • changed className

    Note you will have to do the replacement in the success of the Ajax

    var div = $("#myElement");
    div.replaceWith('<div id="myElement">\
        <ul id="myUl">\
            <li>new content list 1</li>\
            <li>new content list 2</li>\
        </ul>\
    </div>');
    $("#myElement").find("ul").addClass("myClass");
    console.log($("#myElement").html())
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div id="myElement">
        <ul id="myUl">
            <li>content list 1</li>
            <li>content list 2</li>
        </ul>
    </div>