0

This code here is working perfectly fine for the most part. this.content are strings of HTML comeing from JSON.

$(this.content).find('img, a[href$=".jpg"], a[href$=".jpeg"], a[href$=".JPEG"], a[href$=".png"], a[href$=".pdf"], a[href$=".PDF"]').each(function() {

});

For some reason though this string:

Packaged in lots of 10 sets
<img class="alignnone size-full" src="http://www.integra-adhesives.com/wp-content/uploads/2011/03/Sink_Fastener.jpg" alt="" width="300" />

Is making jQuery cause a fit. It is throwing: Uncaught Error: Syntax error, unrecognized expression:

I am using jQuery v2.1.1.

Can anyone help?

marcusds
  • 784
  • 1
  • 7
  • 26
  • I've had this error before, if I can recall properly, has something to do with the unescaped forward slash. Will look in to. – Jester Sep 05 '14 at 23:03
  • 1
    http://stackoverflow.com/questions/14347611/jquery-client-side-template-syntax-error-unrecognized-expression – lesssugar Sep 05 '14 at 23:04
  • @lesssugar, I'm running 2.1.1, so the problem there is fixed already, but I did find a solution there anyhow. See my answer. – marcusds Sep 05 '14 at 23:15

3 Answers3

2

$(something) can work in two ways: if something is an HTML string, it parses it into DOM elements; if it's a selector, it searches the current DOM for elements matching that selector. If something begins with and HTML tag then it's an HTML string, otherwise it's assumed to be a selector. Your string begins with Packaged, which isn't an HTML tag, so the string is processed as a selector, and it's not a valid selector.

You should use:

$('<div>' + this.content).find(...);

so that the content will always be treated as HTML.

You even need to do this if the string does start with <, because find() only searches for descendants. If your string were something like:

<img src="someURL">

and you did:

$(this.content).find("img");

it wouldn't find it, because the image is the top-level element.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks @Barmar, I found this out myself just before you posted your answer. I found a better way however of solving it. – marcusds Sep 05 '14 at 23:20
2

I fixed this by adding this.content = $.parseHTML(this.content); beforehand.

As Barmar points out this is because jQuery is trying to use the string as a selector.

marcusds
  • 784
  • 1
  • 7
  • 26
1

The problem is that jQuery can't tell if your HTML is a selector expression or HTML.

From the jQuery docs (emphasis mine): http://api.jquery.com/jQuery/#creating-new-elements

If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it starts with <tag ... >). If not, the string is interpreted as a selector expression, as explained above.

So for your HTML to be recognized as HTML you should make sure it doesn't start with a text node. You could wrap all of your HTML in <span></span> tags just to be safe.

pseudosavant
  • 7,056
  • 2
  • 36
  • 41