4lackof 4lackof - 1 month ago 4x
HTML Question

JS - document.querySelector() || document.querySelector() gives type error

I have the following code (dummy) :

myFunction(document.querySelector('[data-param="param1"]').textContent || document.querySelector('[data-param="param2"]').textContent);

What is supposed to do is if
exists, use that one, else, use
by exploiting the use of
. I know this is not the best to use (see here), but it is what I came up with for my circumstances.

I attempted to make a jsfiddle to demonstrate this; however, the error is wrong, although this could just be different wording in the consoles as I am using two different browsers (don't ask).

In Firebug it says:

TypeError: document.querySelector(...) is null

and in Chrome it says:

TypeError: Cannot read property 'your-property-here' of null

I thought I had it working with
document.getElementById('param1') || document.getElementById('param2')
but what the jsfiddle is giving does not seem to work on either

I could not find anything about this on the docs, and my google searching did not find anything...

Is this a feature or a bug? Is there event a way to exploit
values on
, etc)? What would be the best way to go about doing what I want it to do?


The reason you see the error is because your first query is returning null, and thus it has no property dataset. Try this instead:

(document.querySelector('[data-example="example1"]') || document.querySelector('[data-example="example2"]')).dataset.example

Now if document.querySelector('[data-example="example1"]') is returning null, it will try document.querySelector('[data-example="example2"]') instead. You should be aware though, that if both queries return null you will still get the error.