开发者

is there a simple way to check if given selector string point to only one element?

开发者 https://www.devze.com 2023-03-09 15:12 出处:网络
example 开发者_开发技巧$(\'div.mydiv\').checkifonlyone().css(\'background-color\', \'red\'); or maybe

example

开发者_开发技巧$('div.mydiv').checkifonlyone().css('background-color', 'red');

or maybe

$('div.mydiv').filter(':checkifonlyone').css('background-color', 'red');

I expect that there is only one div with that class in document, otherwise an error msg should be displayed and script should cease to execute ?


Could either look like:

$('div.mydiv:eq(0)').css('background-color', 'red');

That one would always select the first element if there are multiple.

or

var $mydiv = $('div.mydiv');
if($mydiv.length === 1) {
   $mydiv.css('background-color', 'red');
}

Which infact only would change the background color if there is exactly one match on the selector.


You can do it yourself:

if ($(something).length !== 1)
    //Waaaah!


var myDivs = $('div.mydiv');
if(myDivs.length === 1)
{
 myDivs.css('background-color', 'red');
}


if ( $('div.mydiv').length == 1 ) ....

Looking for that? Remember the jQuery element is an array of matches that are iterated by most of the functions (or a top element is popped off).


You need size() function.

It will return numbers of elements in your selector and you can then act on that result accordingly.


Depending on your markup, you might be able to use the :only-child selector, but you'll probably have to do something like this :

var $myDiv = $('div.mydiv');
if ($myDiv.length == 1) $myDiv.css('background-color', 'red');
0

精彩评论

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