0

I have parsed xml and I'm using querySelector

for example:

this.querySelector("TYPE").textContent

Sometimes value of this.querySelector("TYPE") is null so previous line returns an error.

What is the most beautiful way to avoid errors?

I'm doing it with something like the following:

example = this.querySelector("TYPE") != null ? this.querySelector("TYPE").textContent : "" //UGLY!

But it is too long and looks bad.

Other way: Own function like findInXml(this, "TYPE"), but when I want to look deeper it's looks that:

findInXml(findInXml(this, "TYPE"), "STH") // UGLY!

I prefer to use it this way for example:

this.findXml("TYPE").findXml("STH") //Looks nice
Itchydon
  • 2,572
  • 6
  • 19
  • 33
Yas
  • 351
  • 2
  • 17
  • I think the one-line conditional statement is fine – JJJ Aug 14 '17 at 16:25
  • Maybe you want to see this: [function chaining](https://stackoverflow.com/a/1099771/6320039) – Ulysse BN Aug 14 '17 at 17:01
  • You are right, but is it possible to check if previous obj is null with that? Does it call function on null element? null.checkNull() to my mind won't work. – Yas Aug 14 '17 at 17:06
  • Calling `querySelector` twice in the one line conditional seems rather wasteful when you only need to call it once. – Adam Jenkins Aug 14 '17 at 18:11

2 Answers2

1

One call to querySelector:

var typeEl;
var example = (typeEl = this.querySelector("TYPE")) ? typeEl.textContent : '';

JSPerf agrees:

https://jsperf.com/nullqueryselector/1

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • @Yas - your goal is not to write beautiful code, it's to write readable code. Readable code = beautiful code, if you haven't gotten to this point yet, you will. The niftiest one liners are absolute hell to discern at a glance. – Adam Jenkins Aug 15 '17 at 16:37
0

Use conditional line statement like :

example = (this.querySelector("TYPE") && this.querySelector("TYPE").textContent) || '';