Reputation: 105
I'm trying to insert HTML strings before and after an HTML string before writing the finished string to the DOM. Here's what I have so far:
var Hello = '<p id="1234">Hello</p>';
var $Hello = $(Hello);
var $HelloGoodbye = $Hello.after('<p>Goodbye</p>');
$('#content').append($HelloGoodbye);
The result is that my #content div only gets the Hello fragment appended.
Thanks in advance!
Upvotes: 1
Views: 91
Reputation: 9691
.after() appends the content to the parent of the selected element. In your case, $Hello is not appended to any element, so .after() has no effect. If you switch the last two lines #content will append "Goodbye too".
Here is a jsFiddle: http://jsfiddle.net/5xQZV/1/
Upvotes: 0
Reputation: 921
If you put Goodbye after the element, it is not in the element. Why don't you replace
var $HelloGoodbye = $Hello.after('<p>Goodbye</p>');
with
var $HelloGoodbye = $Hello.append('<p>Goodbye</p>');
Good luck!
Upvotes: 0
Reputation: 337560
The problem is because $Hello
is a reference to the <p>
element. You are putting the 'Goodbye' <p>
outside of the first, so the $Hello
variable remains unaffected. You need some method of grouping the two together if you want to have them in a single variable. Try this:
var $hello = $('<div></div>');
$hello.append('<p id="1234">Hello</p>');
$hello.append('<p>Goodbye</p>');
$('#content').append($hello);
Upvotes: 1