Reputation: 2789
I'm trying to build a function for adding bread crumbs to my site's navigation. However, right now I have two problems. 1) For some reason the crumb array only holds 2 crumbs at a time, and 2), even though the html elements are stored in the crumbs array, only the new crumb's HTML is rendered. The other crumb renders as:
[object HTMLLIElement]
// script
function add_crumb(name) {
// get current bread crumbs
var crumbs = $('#breadcrumbs ul li').toArray();
// no current bread crumbs, so we don't need an arrow image
if (crumbs.length == 0) {
var new_crumb = "<li class='crumb' style='display:inline'> " + name + " </li>";
} else {
var new_crumb = "<li class='crumb' style='display:inline'><img class='bc_arrow' src='images/icons/breadcrumb_arrow.png' width='19' height='18'> " + name + "</li>";
}
// add new bread crumb to array
crumbs.push(new_crumb);
// render
$('#breadcrumbs').html('<ul>' + crumbs.join('') + '</ul>');
}
Anyways, I've side stepped the second problem by creating a new blank array and calling .innerHTML on each element (even though I don't understand why I have to do this since jQuery's site says the elements are stored like so:
[<li id="foo">, <li id="bar">]
But if someone could please help me figure out why it's only storing two bread crumbs at a time, I would really, really appreciate it.
Thanks
Upvotes: -1
Views: 113
Reputation: 141917
$('#breadcrumbs ul li').toArray();
gives you an array of HTMLLIElements.
You should take a different approach altogether. No need for any arrays:
if($('#breadcrumbs ul li').length){
$('#breadcrumbs ul').append(
"<li class='crumb' style='display:inline'>"
+ name +
"</li>");
}else{
$('#breadcrumbs ul').append(
"<li class='crumb' style='display:inline'>"
+ "<img class='bc_arrow' src='images/icons/breadcrumb_arrow.png' width='19' height='18'>" +
+ name +
"</li>");
}
Upvotes: 2
Reputation: 95062
HTML Element Objects are not strings, you cannot simply concat them to a string using .join
. Try appending them.
$('#breadcrumbs').html('<ul />').find("ul").append(crumbs);
Upvotes: 4