开发者

jQuery selector: exclusive OR

I'm using a set of jQuery selectors to insert some con开发者_StackOverflow中文版tent on a number of different pages; however some pages feature more than one of the selectors, so the content is inserted more than once on the page. For example:

$('div.rColInnerL:first, div.box300.bdr.search:first, h2.blt13:first').before('<div>Hello World!</div>');

Is it possible to use a kind of exclusive-OR in the jQuery selector, to say that only one of these should be used? Many thanks.


You can reduce the set of found elements to the first one:

$('div.rColInnerL:first, div.box300.bdr.search:first, h2.blt13:first')
.first()
.before('<div>Hello World!</div>');


On the surface it would seem like you could use the first()(docs) method to get the first match.

$('div.rColInnerL:first, div.box300.bdr.search:first, h2.blt13:first').first()

Of course this will depend on the first one always being the correct one. Since it seems like there may be some variation in the use of the element that is matched by the selector, it may be an issue.

jQuery does not necessarily return the elements in the order of the selector, but rather in the order of their appearance on the page, so this doesn't necessarily replicate an "exclusive OR" behavior that you're looking for.

To be more precise, you'd need something more explicit:

var el = $('div.rColInnerL:first');
if( !el.length ) {
    el = $('div.box300.bdr.search:first');
    if( !el.length ) {
        el = $('h2.blt13:first');
    }
}

Here's an example of jQuery not returning the elements in the order of the selector:

<body>
    <div id="first">first</div>
    <div id="second">second</div>
</body>
alert( $('#second, #first')[0].id ); // alerts "first" instead of "second"

Even though #second is first in the selector, the first match is shown as the #first element, because it comes first in the document.

Example: http://jsfiddle.net/XxXXc/


The selected answer doesn't work to me.

I used this:

var container = $('div.rColInnerL:first')[0] || 
  $('div.box300.bdr.search:first')[0] || 
  $('h2.blt13:first')[0];

$(container).before('<div>Hello World!</div>');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜