Reputation: 8920
I wrote the following:
var appendCategoreis = function (categories) {
$.ajax({
url: "http://localhost/perouka/index.php/MainController/getCategories",
dataType: 'json',
success: function (data) {
$.each(data, function (item) {
var temp = categories;
$(temp).find(".category-title").text('dsadsa');
console.log($(temp).find(".category-title").text());
$(".categories").append(temp);
});
},
error: function (e) {
console.log(e);
}
});
}
categories
is an html template passed from another function and has the following structure:
<div class="col-md-3">
<h2 class="category-title">Categoria</h2>
</div>
When I am running the above code the console.log prints Categoria, I think that this means that the function above the console.log does not change the text, there are no errors on the console. Any explanation why this is happening?
Upvotes: 0
Views: 81
Reputation: 11824
When passing an HTML string to $()
, it parses it into a new DOM tree.
var a = '<div>';
// this creates a new <div> and sets its text content to 'hello'
$(a).text('hello');
// this creates a new <div> and sets its text content to 'bye'
$(a).text('bye');
similarly:
// creates a new DOM tree from `temp` and sets the .category-title text to 'dsadsa'
$(temp).find(".category-title").text('dsadsa');
// Creates a new DOM tree from `temp` and logs the .category-title text
console.log($(temp).find(".category-title").text());
// .append also creates a new DOM tree when passed a string
// so this creates a new DOM tree which is appended to .categories
$(".categories").append(temp);
Every time you call $(temp)
, you get a new, different DOM node. If you change one, you don't change the others.
What you want to do is: Create the node only once, then use the same node for all your future operations. Something like:
// create a new DOM tree from `temp`
var node = $(temp);
// now use the same node every time
node.find(".category-title").text('dsadsa');
// logs the .category-title text inside `node`
console.log(node.find(".category-title").text());
// append our changed node
$(".categories").append(node);
Upvotes: 1