Hussein
Hussein

Reputation: 42818

jquery find children selector performance

Is there a better way to write this. I'm checking the input of a textarea and trying to find if it contains an object or iframe tags, if not then set var x =1

if ($textareaval.find('iframe').length > 0) {
    alert('iframe')
} else if ($textareaval.find('param').length > 0) {
    alert('object')
} else {
    var x = 1;
    alert(x)

Upvotes: 0

Views: 486

Answers (3)

Mike
Mike

Reputation: 11

Observing that you will only be giving one alert, and therefore assuming that you will only encounter one type, I suggest the following:

    var foundItems = $textareaval.has('iframe, param');
    var alertVal = 1;
    if(foundItems.length){
       alertVal = "object";
       if(foundItems[0].tagName == "iframe")
          alertVal = "iframe";
    }
    alert(alertVal);

This has the advantage of only one traversal and minimal short-circuit logic utilizing the most common properties of the two objects tested. And, it's readable.

Note: the foundItems.length test is NOT testing for existence, as this property will always exist on a javascript collection; but, if it evaluates to 0, that is a false - and any other number is not.

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361849

If you don't care which one it has you could combine the two checks into one:

if ($textareaval.has('iframe, param').length > 0) {
    x = 1;
}

Edit: You say you do care, though, so then no. Your code is fine, no improvement needed.

Upvotes: 0

Vivek
Vivek

Reputation: 11028

i think even you don't need to check length > o.. do like this..

if ($textareaval.has('iframe, param').length) {
   alert('iframe, param')
}else{var x=1;}

Upvotes: 1

Related Questions