Websphere Websphere - 5 months ago 8
Javascript Question

Access new generated content in jquery

been vainely searching for so long for a solution to my problem. in all posts they invoque 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?

thanks a lot for your help
Regards

Answer

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>