Search code examples
javascriptoperatorsnodelistselectors-api

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


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!


Solution

  • 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.