Reputation: 11377
I have a textarea that contains variable html content which is always wrapped in a paragraph (p) tag.
HTML (before appending):
<textarea rows='7' class='form-control' id='comments'><p>My variable HTML content.</p></textarea>
I fetch this content using the following in jQuery:
jQuery:
$('#comments').val();
Now I need to append HTML at the end of this paragraph but inside the p tag.
HTML (after appending):
<textarea rows='7' class='form-control' id='comments'><p>My variable HTML content. Some appended HTML.</p></textarea>
I can of course replace the last 4 characters of the above (which is the closing p tag), then append my HTML and then add the closing p tag again. Can someone tell me if there is a better way to achieve the same in jQuery ?
Many thanks in advance for this, Tim.
Upvotes: 1
Views: 2665
Reputation: 129
Ok. I REALLY love this!
$('#comments').text($($('#comments').text()).append(' a new insert!').text());
Don't look at it too long. Could hurt your eyes :-)
Upvotes: 0
Reputation: 68440
This could do the trick
var html = $('#comments').val();
$('#comments').val(
$(html).append(' Some appended HTML.')[0].outerHTML
);
Upvotes: 2
Reputation: 318362
Parse the string value of the textarea as HTML, and insert whatever you like, then pass the string value of the HTML back
$('#comments').val(function(_, val) {
return $('<div />', {html:val}).find('p').append('content').end().html();
});
Upvotes: 4
Reputation: 1117
You could insert the value into a temporary div, add an element to the <p>
-element inside the temporary div and fetch the renewed content again:
var tmpDiv = $('<div></div>'); //create temporary element
tmpDiv.html($('#comments').val()); // add HTML from textarea
$(someHtml).appendTo($('p', tmpDiv)); // append custom HTML to P inside temp element
newTextAreaValue = tmpDiv.html(); // retrieve new value
Upvotes: 0