0

When I try to add a data-role div-element dynamically in jquery it fails - it shows up but its not formatted any longer. In the html-file you can see where I put the created div-element.

What is wrong and how could I make it work?

htlm-file

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5  /jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-   1.4.5.min.js"></script>
<script src="my_js.js"></script>
</head>
<body>

<!-- jquery mobile-pages does not work here-->
<div id="mydiv">

</div>


<!-- this works just fine -->
<div data-role="collapsible">
<h4>B</h4>
<ul data-role="listview">
   <li><a href="#">Billy</a></li>
   <li><a href="#">Bob</a></li>
</ul>
</div>

</body>
</html>

jquery

    var string = "" +
    "<div data-role='collapsible'>" +
        "<h4>B</h4>" +
        "<ul data-role='listview'>" +
            "<li><a href='#'>Billy</a></li>" +
            "<li><a href='#'>Bob</a></li>" +
        "</ul>" +
    "</div>";
console.log(string);
$(string).appendTo("#mydiv");

enter image description here

the upper part of the image is when it's created dynamically, the lower part is what it looks like if I just put the code in the html-file. To the right you can see the string which i append to the div

1 Answer 1

2

You have to bind collapsible element when you add it dynamically.

Like :

$(string).appendTo("#mydiv");
/** Add this line and try **/
$("data-role='collapsible'").collapsible();

Ref Link : https://api.jquerymobile.com/collapsible/

Sign up to request clarification or add additional context in comments.

4 Comments

tried but I get syntax error unrecognized expression "data-role='collapsible'" in the console log
Can you just give id or class to your collapsible element and try binding with that? Like : $('#mynewelem').collapsible();
When you create them dynamically, your don't need the data-role thing any more. Just give them a class and call the collabsible()-function on them: $( ".selector" ).collapsible(). Ref: api.jquerymobile.com/collapsible
I tried to wrapp a class-element around mydiv and tried with $(".myclass").collapsible(); but it doesnt help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.