Skip to content Skip to sidebar Skip to footer

Use Javascript To Dynamically Replace Html Tags With More Complicated Code

I was wondering whether there is a good way of attaining the following: I select a HTML class, marked with a certain CSS class (say My content

Solution 1:

If you want to repalce the HTML rather than the text content, you can always use the replaceWith() function:

var newContnet = '<h1>My Title</h2> My con<img src="myimage.jpg">en<img src="myimage.jpg">';

$( ".myClass" ).replaceWith(newContent);

And here is a super-simple example:

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function(){
          var newContnet = '<h1>My Title</h2> My con<img src="myimage.jpg">en<img src="myimage.jpg">';
          $(".myClass").replaceWith(newContnet);
        });
        </script>
    </head>
    <body>
        <span class="myclass" data-image="myimage.jpg" data-title="My Title">My content</span>
    </body>
</html>

Post a Comment for "Use Javascript To Dynamically Replace Html Tags With More Complicated Code"