Could someone tell me why this code does not update the data response? It’s a simple example of the each function.
Here is the ajax requested html file:
<html>
<div class="new">
<div class="span4">
<h2>Heading1</h2>
<p>Text1</p>
<p><a href="#">Link1</a></p>
</div>
<div class="span4">
<h2>Heading2</h2>
<p>Text2</p>
<p><a href="#">Link2</a></p>
</div>
</div>
</html>
and here is the main file body:
<!DOCTYPE html>
<body>
<textarea id="gethtml" rows="40" cols="125"></textarea>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
"use strict";
$(function() {
$.get('file.html', function(data) {
ajaxfunction(data);
});
function ajaxfunction(data) {
$(data).find(".span4").each(function () {
$(this).find("p").eq(0).text("Hello");
$(this).find("p").eq(0).after("<p>newline</p>");
console.log($(this));
});
$("#gethtml").val(data);
}
});
</script>
</body>
</html>
You can see that the console displays the correct data for each span4, but why doesnt the “data” string gets updated to reflect the changes?
EDIT
function ajaxfunction(data) {
var tree = $("<div>" + data + "</div>");
$(tree).find(".span4").each(function () {
$(this).find("p").eq(0).text("Hello");
$(this).find("p").eq(0).after("<p>newline</p>");
console.log($(this));
});
$("#gethtml").val(tree.html());
}
This places in the textarea, ie <p>Hello</p><p>newline</p>.
So, in order to also put a new line into it, then I’ll have to modify it as a string, right?
Thanks!
datais a string.Your
eachcode parses this string into a DOM tree and modifies it.However, you don’t do anything with this DOM tree.
Your
val()call uses the original string again.Instead, you need to call
html()to get the source of the modified DOM tree.For more information, see my blog post.