How to set a variable depending on which nodeList is not empty in JavaScript?

116 views Asked by At

I'm wondering if there is a nicer way to do this:

I'm trying to set target to either "[data-update]" or div.ui-content to be found within an element.

Originally I wanted to do something like this:

target = el.querySelectorAll("[data-update]") || el.querySelectorAll("div.ui-content");

But this will not work, because the first expression will always be defined, even if it is an empty nodeList [].

So now I have this, which works, but I'm not happy with it:

target = container.querySelectorAll("[data-update]")

if (target.length === 0) {
  target = container.querySelectorAll("div.ui-content");
}

if (target.length === 0) {
  util.errorHandler({"error": "updatePageSection: No target found"});
} else {
  // do stuff
}

Question:
Is there an easier way to do this? Pure JavaScript only.

Thanks!

2

There are 2 answers

0
JotaBe On BEST ANSWER

Use the conditional operator, and check the length of the selection:

target = el.querySelectorAll("[data-update]").length
     ? el.querySelectorAll("[data-update]")
     : el.querySelectorAll("div.ui-content");

Basically a ? b : c means if a is true, take b, else take c. More infor on: Contional operator.

Besides, if you don't want to repeat the first selection, you can add an extra step:

target = el.querySelectorAll("[data-update]");
target = target.length ? target : el.querySelectorAll("div.ui-content");

The first tme you see this syntax is really strange. But you'll soon get used to it.

NOTE: in JavaScript, zero is treated as false. And a none-zero number is treated as true.

0
Ivan Chernykh On

You can do this:

target = ( el.querySelectorAll("[data-update]").length>0 && 
           el.querySelectorAll("[data-update]") ) || 
         ( el.querySelectorAll("div.ui-content").length> 0 && 
           el.querySelectorAll("div.ui-content") );

But it is absolutely unreadable and too much DOM calls. But "one-line". Fiddle: http://jsfiddle.net/3X2Nd/