jQuery stop append removing div - javascript

I am copying a div into another div using append. However it removes the original. I tried to use clone but it seems to only work with appendTo. But appendTo breaks my layout so I have to use append with works fine.
I am wrong that clone will not work with .append and is there another way to stop the div removing?
Thanks
$('.compareWrapper').append(htmlStr)

foo.appendTo(bar)
Take foo and append it to bar.
foo.append(bar)
Take bar and append it to foo
Syntactically they're different. You have to think of what's the target object and what's the destination object. So, having said that you can move ahead in one of two ways:
var $clone = $('target').clone();
$clone.appendTo('wrapper');
$('wrapper').append($clone);
Both do the same thing.

The following does not work?
$('.compareWrapper').append($(htmlStr).clone());

I don't see any reason for .clone() not working with .append(). The code should be:
$('.compareWrapper').append($(htmlStr).clone());
Is that what you tried? From the name of your variable, I'm assuming htmlStr is a string, not a jQuery object.

Related

Cloning and inserting tags using JS

I'm trying to clone a <div> html tag and to insert it after the original one using JavaScript, but I can't fix it. Can you help me please ?
JavaScript code :
var divo = document.getElementsByTagName('div')[0];
var divc = divo.cloneNode(true);
document.getElementByTagName('body')[0].appendChild(divc);
Here is the fiddle : http://jsfiddle.net/8Kab6
Thanks in advance.
Use the original element's parentNode function to get its parent, and then use appendChild to add it after.
var divo = document.getElementById('divTP1');
var divc = divo.cloneNode(true);
divo.parentNode.appendChild(divc);
jsFiddle
Using getElementsByTagName isn't necessary since you have the reference to divo that you already need for the appending function. calling getElementsByTagName again requires the browser to do another search through the DOM (albiet an easy one).
Also you don't need to use getElementsByTagName at all since you only want one element and it has an id. Better to use getElementById.
This is the most efficient code.
Correct getElementByTagName as below, that will produce the desired result
document.getElementsByTagName('body')[0].appendChild(divc);
The error with your original code was a missing "s" on the last line..
document.getElementByTagName('body')[0].appendChild(divc);
should read
document.getElementsByTagName('body')[0].appendChild(divc);

To get complete html of page except few div's with particular class

I want to get complete html of page in javascript except few div's with particular class applied on them.I am using this to get the complete html of my document
$(window.document.documentElement).html().toString()
You can try:
$(document).contents().not('.aClass').foo()
I'd suggest the following:
var html = $('html').clone(true);
html.find('.remove').remove();
console.log(html)​
JS Fiddle demo.
Note that if you then try chaining html.toString() you'll end up with the string [object Object], not the HTML. If you you add .toString() after the remove(), in Chrome, you seem to end up with exactly the same object being passed to the console.
References:
clone().
find().
remove().
You first create a copy of the documentElement, by using .clone() and storing it in a variable.
In the copied document you remove the elements you want.
var doc = $(window.document.documentElement).clone();
doc.find('.remove').remove();
console.log(doc.html());​​​​​
http://jsfiddle.net/ZnMyj/

Add DOM elements to beginning of parent

I have the following javascript working to insert AJAX responses into a div with id results:
document.getElementById("results").innerHTML=xmlhttp.responseText;
However, this adds all new elements after those already present. I need for the new elements to be inserted before everything else.
I know this is probably very trivial but I can't seem to find anyway to do it myself.
Thanks for any help!
With modern js you can utilize the prepend method. Currently caniuse.com says only of IE, Edge, and OperaMini are not supported.
ParentNode.prepend(nodesToPrepend);
e.g.,
ParentNode.prepend(newDiv);
Also, it automatically converts text into a text node so you could do the following for your use case:
document.getElementById("results").prepend(xmlhttp.responseText);
You want either this
results.insertAdjacentHTML( 'beforebegin', xmlhttp.responseText );
or this
results.insertAdjacentHTML( 'afterbegin', xmlhttp.responseText );
(the variable results of course being a reference to the DOM element)
So, the first one will insert the new content before the element itself (as a previous sibling), and the second one will insert it inside the element before any other children).
I don't remember the exact syntax, but it something like:
var newDiv = document.createElement("div");
newDiv.innerHTML=xmlhttp.responseText;
document.getElementById("results").childNodes.addAt(0,newDiv);
if you can use jQuery, it's just simple as:
$("#results").prepend(xmlhttp.responseText);

Opposite of append in jQuery

I use .append to add to a div
$(this).append('<ul><li>test</li></ul>');
how can I search for a <ul> and remove it if it exists in the children of $(this)?
You could use remove(). More information on jQuery remove().
$(this).children("ul").remove();
Note that this will remove all ul elements that are children.
The opposite of .append() is .prepend().
From the jQuery documentation for prepend…
The .prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use .append()).
I realize this doesn’t answer the OP’s specific case. But it does answer the question heading. :) And it’s the first hit on Google for “jquery opposite append”.
Use the remove() method:
$(this).children("ul").remove();
What you also should consider, is keeping a reference to the created element, then you can easily remove it specificly:
var newUL = $('<ul><li>test</li></ul>');
$(this).append(newUL);
// Later ...
newUL.remove();
just had the same problem and ive come across this - which actually does the trick for me:
// $("#the_div").contents().remove();
// or short:
$("#the_div").empty();
$("#the_div").append("HTML goes in here...");
Opposite up is children(), but opposite in position is prepend().
Here a very good tutorial.

jQuery wrap syntax

It's end of day. I'm hoping I'm just having a lapse of logic.
I can't get this to work:
var $divA= $("<div></div>").addClass('classA');
var $divB= $("<div></div>").addClass('classB');
$myDiv.after($divA.wrap($divB));
The above should turn this:
<div id="myDiv"></div>
Into this:
<div id="myDiv"></div>
<div class="classB">
<div class="classA"></div>
</div>
But it doesn't seem to work with that 'wrap' in there. I don't get any errors, it just doesn't wrap divA with divB and just inserts divA by itself.
Am I misunderstanding wrap?
UPDATE:
A simpler example that does not work:
$myBox.after($("<p></p>").wrap("<div></div>"));
That will add just the DIV after myBox.
It seems like jQuery doesn't like wrap added to after.
Have you tried
$myDiv.after($divA.wrap('<div class="divB"></div>'));
just for testing purposes?
As far as I understand, you shouldn't pass a jQuery object to the wrap-function:
The .wrap() function can take any
string or object that could be passed
to the $() factory function to specify
a DOM structure. This structure may be
nested several levels deep, but should
contain only one inmost element. The
structure will be wrapped around each
of the elements in the set of matched
elements.
If the example above works, then this is the reason ;-)
Just stumbled onto this thread having the same problem: jQuery .wrap() isn't working
I think if you change your code from
$myDiv.after($divA.wrap($divB)) to $myDiv.after($divA.wrap($divB).parent())
you'll get your wrap.
The confusing part might have been to You that .wrap() returns the inner element, not the parent element.
So you have to use the parent object of the wrapped one like this:
var $divA= $("<div/>").addClass('classA'),
$divB= $("<div/>").addClass('classB');
$myDiv.after($divA.wrap($divB).parent());
($divA.parent() is equal to $divB after the wrapping)
So the key part is that $divA.wrap($divB) returns $divA, NOT $divB
see the reference:
This method returns the original set of elements for chaining
purposes.
http://api.jquery.com/wrap/
I got this to work:
$('div#myDiv').after("<div class='classA'></div>").end().find('.classA').wrap("<div class='classB'></div>");
with your html to solve your initial question. Here's the source for jQuery's end function. This code will go make the chain go up one level (to the myDiv level), and will then wrap based on the find('.classA') at that level. That will find your div added with after, and wrap it in div with classB.
Edit:
Ok, I think this will work for you the way you want:
var divA= $("<div></div>").addClass('classA');
$('div#myDiv').after($(divA).wrap('<div class="divB" />'));
I think the problem was that when calling wrap on divA, it needs to be a jQuery object to work correctly. So really all you were missing was wrapping divA in ().
You're not looking for wrap. You want:
divB.append(divA).insertAfter('#myDiv');
I may be reading this wrong, but if you're using jQuery, isn't the $ a reserved character? have you tried just setting your variable names so they don't use it?
If so:
var divA = $("<div></div>").addClass('classA');
divA.wrap("<div class=\"classB\"></div>");
divA.insertAfter($("#myDiv"));
or
divA.after($("#myDiv"));
Here's the jQuery docs on the matter.

Categories

Resources