You need to enclose special characters in quotes when using a attribute based selector.
if ($('ul li a[href=""https://stackoverflow.com/questions/31197452/+ id +""]').length) {
Your version of selector would result
if ($("ul li a[href=#!...]").length) {
The #!
will throw unrecognized expression.
My version where the ""
escape the characters
if ($('ul li a[href="#!..."]').length) {