Nick Nick - 25 days ago 10
jQuery Question

jquery unwrap - unrecognized expression

I have a very simple function that wrap or unwrap the logo from a bootstrap navbar according to the screen size.

Basically, on mobile the logo is on the left, on desktop is in the middle.

Here's the function:

var checkLogo;

checkLogo = function() {
var logo, logoId, w;
w = window.innerWidth;
logoId = $('#logo').length;
logo = "<li id='logo'></li>";
if (w < 768) {
if (logoId !== 0) {
$('.navbar-brand').unwrap(logo);
return $('.navbar-brand').insertAfter('.navbar-toggle');
}
} else {
if (logoId === 0) {
$('.navbar-brand').wrap(logo);
return $('#logo').insertAfter('.navbar-nav li:nth-child(2)');
}
}
};

$(document).ready(function() {
return checkLogo();
});

$(window).resize(checkLogo);


As I said, the function is very straight forward and it actually works.

The problem I've got is when unwrapping the element. It still works, but i get this error and I don't understand why.


Uncaught Error: Syntax error, unrecognized expression: (…)


Do you have any suggestion?

If i remove the id, the error disappears, but ideally i need to be able to append a specific ID as well.

Thanks

Answer

jQuery's unwrap() only takes one single argument

A selector to check the parent element against. If an element's parent does not match the selector, the element won't be unwrapped.

Passing in HTML like <li id='logo'></li> is not a valid selector to check the wrapping elements against, if you wanted to make sure that you only unwrap that element, you'd do

$('.navbar-brand').unwrap('#logo');