JQuery Syntax error, unrecognized expression: ,

8.4k Views Asked by At

I'm trying to simply add a comma after each element in a list.

$('#tag_cloud-2 div.tagcloud a').each(function(){
  console.log($(this));
  $(", ").after($(this));
});

The console spits out the tags so I know it is finding them. I've tried insertAfter as well, but with no luck. This seams like it should be such a simple thing to do!! Thanks for pointing out what I'm missing.

2

There are 2 best solutions below

0
On BEST ANSWER

$(', ') is treated as selector(invalid), because it can't create text node with containing string.

But

$("<span>, </span>").after($(this)); will work because of a valid markup.

Try:

$(this).after(', ');

OR

$(this).append(', ');

OR

$(this).text(function(i, oldText) {
  return oldText + ', ';
})
0
On

jQuery's $() function doesn't quite work like that. Calling it on a non-markup string does not create a text node containing that string.

You can invert your logic, start from $(this), then call after(), though:

$(this).after(", ");

Because after() creates a new text node if one of its arguments is a non-markup string.