Following is a code snippet which creates a wrapper div
then appends a pre
element inside that. However this does not seem to work.
var t = $('#t');
var container = $('<div>');
container.css('position', 'relative');
t.wrap(container);
var pre = $('<pre>');
pre.appendTo(container); // Seems to have no effect
When I run this code and inspect the elements I see no pre
element.
The working demo can be seen here - http://jsfiddle.net/ueb2pq6o/
Why is the pre DOM not getting appended?
Because wrap
creates a copy of the element(s) you give it, it doesn't use the originals. From the docs :
A copy of this structure will be wrapped around each of the elements in the set of matched elements.
You can readily fix it by using t.parent()
instead of container
:
pre.appendTo(t.parent());
var t = $('#t'); var container = $('<div>'); container.css('position', 'relative'); t.wrap(container); var pre = $('<pre>'); pre.appendTo(t.parent()); // <== Change is here
textarea { border: 1px solid black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <textarea id="t" row="1" style="resize:none;"></textarea>
Alternately, use insert the container before the textarea and then use append
:
container.insertBefore(t);
t.appendTo(container);
var t = $('#t'); var container = $('<div>'); container.css('position', 'relative'); container.insertBefore(t); // <== Change is here t.appendTo(container); // <== and here var pre = $('<pre>'); pre.appendTo(container);
textarea { border: 1px solid black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <textarea id="t" row="1" style="resize:none;"></textarea>
You wrapped t
using container
though container
ain't actually added to DOM. use class or ID to specify where to add pre
var t = $('#t');
var container = $('<div id="foo">');
container.css('position', 'relative');
t.wrap(container);
var pre = $('<pre>');
pre.appendTo("#foo");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.