I have this HTML structure in a page and an AJAX request returns the same structure:
<div id="feeds">
<div class="items">
<div class="feedClass">
content
</div>
<div class="feedClass">
content
</div>
<div class="feedClass">
content
</div>
</div>
<div class="pager">
content
</div>
<div class="keys">
content
</div>
</div>
Contents of data are the same as above.
How can I replace this JavaScript code with a more efficent code to append the stuff in items to the current items, and replace the content in pager and keys. I have this so far, data
is what is returned by the AJAX request:
var itemsFirstChildTag = $(id + " .items:first-child").get(0).nodeName;
var id = "#feeds";
$(".items", id).append($(id + " .items > "+itemsFirstChildTag, "<div>"+data+"</div>"));
$(".keys", id).replaceWith($(id + ".keys", "<div>"+data+"</div>"));
$(".pager", id).replaceWith($(id + ".pager", "<div>"+data+"</div>"));
I would try looking into using a better communication method, such as JSON or XML. That alone would make this whole ajax request a LOT more efficient. The idea being you can append the data
you are returning to the appropriate location, you do not need to be returning any HTML.
$.ajax({
type: 'post',
url: 'some-script.php',
success: function( response ){
//neat jquery element creation
var newFeed = $("div", {
"class" : "feedClass",
"text" : response.newText
});
$(".items").append(newFeed);
$(".keys").text(response.newText);
}
});
If you need to modify the text of an element you can use .text().
Get:
$(".some-class").text();
Set:
$(".some-class").text("Some Text");
If you need to modify the HTML of an element, use .html()
GET/SET same as $.text()
In short I'd definitely recommend reading as much of the jQuery documentation as you possibly can, there are a lot of neat tricks/demo's there.
var feeds = document.getElementById("feeds"); var feeddivs = feeds.getElementsByTagName("div"); var len = feeddivs.length; for(var i=0;i
}