PHPLover
PHPLover

Reputation: 12957

How to add text between div using jQuery?

I've following HTML code:

<div class="modal-body">
<p style="text-align: justify;">Some text paragraph</p>
<br/>
<form></form>
</div>

I want to add following HTML dynamically to above HTML after <br/>. How should I do?

<div class="alert alert-danger alert-dismissible" role="alert">
      <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
    response<!-- response is the variable containing the text to be added--->
    </div>

Upvotes: 0

Views: 2652

Answers (2)

David Thomas
David Thomas

Reputation: 253318

To insert HTML to a given element, in this case (it appears) div.modal-body, from a string of HTML (var htrmlString = "<div><button>...</button></div>", for example), you can use prependTo() or prepend():

$(htmlString).prependTo('div.modal-body');

Or:

$('div.modal-body').prepend(htmlString);

Similarly, though slightly more complex, you could use:

$(htmlString).insertBefore('div.modal-body:first-child');

The following is the original answer to original version of the question (since edited by OP to correct it).

The easiest solution would be:

$('div.alert.alert-danger.alert-dismissible').append(response);

Though you could also (if you don't mind losing all bound event-handlers, and recreating your DOM):

$('#div.alert.alert-danger.alert-dismissible').html(function (index, html){
    return html + ' ' + response;
});

Note that you appear to be confused by CSS selectors:

  • #alert-danger: selects an element with id="alert-danger", whereas:
  • .alert-danger: selects elements with a class of, or including, alert-danger.

The selector I used, above, div.alert.alert-danger.alert-dismissible selects <div> elements that have each of the classes specified (alert, alert-danger and alert-dismissible).

References:

Upvotes: 1

Vadim S
Vadim S

Reputation: 358

You must use append method and use class instead of id in selector:

$('.alert-danger').append(response);

Upvotes: 0

Related Questions