Reputation: 39
I want build a dynamic HTML elements. All works well, no errors, but the result when I display the content:
<div class="search-result">
[object Object][object Object][object Object][object Object][object Object]
<span class="ionicon ion-ios-close-outline"></span>
</div>
My code:
$('form.search-form a.btn').on('click', function(e) {
e.preventDefault();
if ($('div.search-result')) {
$('div.search-result').remove();
};
var $searchResult = $("<div/>", {
"class": "search-result"
});
var $searchClose = $("<span/>", {
"class": "ionicon ion-ios-close-outline"
});
var $html = '';
$term = $.trim($('#myInput').val());
$filter = $term.toUpperCase();
$('span.aliment-title').each(function(index) {
$txtValue = $(this).text();
if ($txtValue.toUpperCase().indexOf($filter) > -1) {
$html += $(this).clone();
}
});
$searchResult.html($html);
$('header.site-header').append($searchResult);
$searchResult.append($searchClose);
});
Upvotes: 1
Views: 43
Reputation: 10096
$html += $(this).clone();
returns an object, so $html += $(this).clone();
adds the String representation of the object to your html variable, which is always "[object Object]", what you probably want is $html += $(this).clone()[0].outerHTML;
or simply $html += this.outerHTML;
which accesses the html element.
So in full your code would look like this:
$('form.search-form a.btn').on('click', function(e) {
e.preventDefault();
if ($('div.search-result')) {
$('div.search-result').remove();
};
var $searchResult = $("<div/>", {
"class": "search-result"
});
var $searchClose = $("<span/>", {
"class": "ionicon ion-ios-close-outline"
});
var $html = '';
$term = $.trim($('#myInput').val());
$filter = $term.toUpperCase();
$('span.aliment-title').each(function(index) {
$txtValue = $(this).text();
if ($txtValue.toUpperCase().indexOf($filter) > -1) {
$html += this.outerHTML;
}
});
$searchResult.html($html);
$('header.site-header').append($searchResult);
$searchResult.append($searchClose);
});
Upvotes: 1
Reputation: 18973
$searchResult
is object, you can get div content by $searchResult.outerHTML()
Change your line of code to
$('header.site-header').append($searchResult.outerHTML());
Upvotes: 1