简体   繁体   中英

how to put html inside script tag and show it using jquery

Please is it possible to load some HTML element inside script tag and access any one of it using the class name

<script id="scripttags">
    <div class="item-1">Hello</div>
    <div class="item-2">Hello2</div>
    <div class="item-3">Hello</div>
</script>

Access it:

<script>
    var loadit = $('script#scripttags item-2').clone();
    alert(loadit);
<script>

Please is there anyway I can do this?

Use handlebars.js to create template. Bind it to json data after compilation. Then, you can show html. You can also use other templating libraries like mustache.js, underscore.js template etc.

The code below is from http://handlebarsjs.com

<script id="entry-template" type="text/x-handlebars-template"> 
<div class="entry"> 
<h1>{{title}}</h1>
 <div class="body">
 {{body}} 
</div> 
</div> 
</script>

This defined the template. Then, you can use it as shown below.

   <script type="text/javascript">
    var source = $("#entry-template").html(); 
    var template = Handlebars.compile(source);
    var context = {title: "My New Post", body: "This is my first post!"}; 
    var html = template(context);
    </script>

You can do like this:

$("body").html(
   '<div class="item-1">
     Hello
    </div>

    <div class="item-2">
    Hello2
    </div>

    <div class="item-3">
    Hello3
    </div>'
  );

Here, in the body the desired alement can be added/assigned/appended.

I recommend to use handlebars but it also can be done with pure js/jquery:

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <script id="scripttags" type="text/html"> <div class="item-1">Hello</div> <div class="item-2">Hello2</div> <div class="item-3">Hello</div> </script> <script type="text/javascript"> var el = $( '<div></div>' ); el.html($('#scripttags').text()); var loadit = el.find('.item-2').html(); alert(loadit); </script> </body> </html> 

I put the content of your script tag in a dynamically created div and at this moment it behaves like normal DOM

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM