Question

I'm having problems with the following: http://jsfiddle.net/x55LD/1/

I'm trying to parse custom tags using jQuery 1.6. It's working properly, except when a tag is located within a <select> tag. For example:

var string = '<div><blah></blah><select><blah></blah></select></div>';

$(string).find('blah').each(function() {
    console.log("Found tag!");
});

This will only log one message, despite the presence of two <blah> tags. The second <blah> tag within the <select> won't be recognized. Does anyone know why this might be happening?

Was it helpful?

Solution

The problem is that it's not JavaScript or jQuery that does the parsing, it's the browser. Though you may consider that <select> tag to be your own custom deal, the browser disagrees and expects it to contain only <option> or <optgroup> tags.

When you wrap the string up via jQuery like that, what's happening internally is that jQuery is handing the string over to the browser as the "innerHTML" of a temporary element. The browser expects that it's got HTML to work on, so when it sees illegal markup it handles it basically however it wants to. Maybe some browsers would leave the <blah> tag alone, but others won't.

OTHER TIPS

As an alternative to using invalid HTML, use custom attributes to mark tags or store data instead, e.g.

<div><span blah></span><select blah></select></div>

Then you can use the attribute selector:

$('[blah]')...

You can also use HTML5 style attributes like data-something="my data" and use the $.data to obtain the value directly.

Since the contents of a nonstandard tag is probably just going to be rendered anyway, there's no difference in doing that versus just using a span tag with a custom attribute. I'm not sure what you're trying to achieve exactly with a custom tag inside an option group, but I wouldn't think you want it to be rendered, so probably a custom tag on a the select or a specific option would achieve your goal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top