HTMLタグに囲まれていないテキストはfirstChild.data.trim()で取得

HTMLタグに囲まれていないテキストを取得

突然ですが問題です。

以下のfooのテキスト部分をJavaScriptで取得するにはどうすれば良いでしょうか?

<p>
  foo
  <span>test</span>
  bar
</p>

spanタグ内であればdocument.querySelector('span').textContentだがfooの部分だけ取得するというのは解答できない人が多いかもしれない。

答えはfirstChild.data.trim()

答えはfirstChild.data.trim()を使用して以下のように取得する。

ちなみにlastChild.data.trim()を使用すればうしろのbarの部分だけ取得できる。

var p = document.querySelector('p');
var a = p.firstChild.data.trim();
var b = p.lastChild.data.trim();
console.log(a); // => foo
console.log(b); // => bar