4

I've seen that you can dynamically add HTML with jquery:

$( "div" ).append( "<p>Test</p>" );

What would be the way to dynamically add somewhat more complicated HTML:

<blockquote class="col-sm-9">
  <p class="lead">Lorem Ipsum</p>
  <footer>Lorem Ipsum <cite title="Source Title">Lorem Ipsum</cite></footer>
</blockquote>
3
  • 2
    depends on use case ... numerous ways to do it. Can clone existing. Can use template scripts. Can use strings. Can put html in a script tag and pull it from there. Can use ajax from server. What are you trying to do? Commented Jan 28, 2016 at 5:44
  • does it matter if the html is complicated ? cant you simply use the class name to append whatever html is Commented Jan 28, 2016 at 5:44
  • 1
    i mean if we put your html in hidden div and retrieve your html as var Your_HTML=$(".ur_hidden_div_class").html(); and than append it whereever Commented Jan 28, 2016 at 5:48

3 Answers 3

8

this is how I normally do it (simple and readable), unless there is an id in the markup

var html = '<blockquote class="col-sm-9">';
html += '<p class="lead">Lorem Ipsum</p>';
html += '<footer>Lorem Ipsum <cite title="Source Title">Lorem Ipsum</cite></footer>';
html += '</blockquote>'

$( "div" ).append( html );

if you also want to assign unique id while appending it then

var blockQuoteCounter = 0;
var html = '<blockquote class="col-sm-9" id="blockQuote_' + blockQuoteCounter + '">';
html += '<p class="lead">Lorem Ipsum</p>';
html += '<footer>Lorem Ipsum <cite title="Source Title">Lorem Ipsum</cite></footer>';
html += '</blockquote>'

$( "div" ).append( html );
Sign up to request clarification or add additional context in comments.

Comments

0
    <html>
<head>
    <title>sample Page</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>

<script>

    $(document).ready(function () {

        $('#btnAdd').click(function () {
            var szData = "";
            szData = '<blockquote class="col-sm-9">  <p class="lead">Lorem Ipsum</p>';
            szData = szData + '<footer>Lorem Ipsum <cite title="Source Title">Lorem Ipsum</cite>';
            szData = szData + '</footer></blockquote>';

            $('div').append(szData)
        });



    });


</script>
</head>
<body>
    <input type="button" value="Add Data" id="btnAdd"/>
  <div></div>
</body>
</html>

Comments

0

this is a answer for how to display html code in javascript

$( "#update" ).append( 'You have 5 tokens remaining for this coupon. Would you like to Update the unused tokens? Please select quantity you would like to Update.”{{ csrf_field() }} Update Coupon Quantity. Recover Unused Coupon.Close');

Comments

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.