JQuery append () does not add
I have html structure:
<div id="things">
<div class="whatever">
<div class="frame">content</div>
<div class="frame">content</div>
<div class="frame">content</div>
</div>
</div>
And I got JS with a JQuery script that works when a button is clicked on this page:
function intsaver(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "intsaver.php", true);
var tosf = $('<div></div>');
$("#things").find(".frame").each(function(){
tosf.append($(this).innerHTML);
alert(''+tosf);
});
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data=" + tosf.innerHTML);
}
I can see the content this
in the debugger, which is exactly what I am looking for. But it tosf
remains undefined
, and on the server side I get undefined
.
I tried several ways, for example I added this
myself. As a result, the div disappeared from the page, but tosf
remained undefined
.
I believe I made a clear mistake.
source to share
Try
function intsaver() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "intsaver.php", true);
var tosf = $('<div></div>');
$("#things").find(".frame").each(function () {
tosf.append(this.innerHTML); //innerHTML is a property dom element
alert('' + tosf);
});
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("data=" + tosf.html()); //tosf is a jQuery object os call .html()
}
source to share
A bit more explanation of why .innerHTML
doesn't work. As stated in the answers $(this).innerHTML
won't work as jQuery doesn't have this property. But if you customize your code, you can also take advantage of .innerHTML
. If you wrap the item with $(element)
, it creates a specific jQuery object, and you need to get out of his element if you want to use .innerHTML
as: $(this)[0].innerHTML
. Since this
is only an element in this jQuery array, it this.innerHTML
will suffice without doing $(this)
. so your code could be:
function intsaver(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "intsaver.php", true);
var tosf = $('<div></div>');
$("#things").find(".frame").each(function(){
tosf.append(this.innerHTML);
alert(''+tosf);
});
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data=" + tosf[0].innerHTML);}
source to share