Wonderful! WordPress

文字列のHTMLをDOMオブジェクトに変換

Javascript DOMParser

文字列として持っている HTML のソースコードは、当たり前のことではあるけれど、そのままでは DOM オブジェクトして扱えない。DOM オブジェクトして扱いたいというのは、たとえば、親要素に append とか prepend させたいとか、style を設定するとか。

たとえば、文字列としての HTML ソースコードというのは、これから append させたくて変数に入れている以下のようなもの。

const pager = '<nav id="pagenavilist"><span class="pages">1/7</span><span class="current">1</span><a href="http://localhost/wp/?paged=2" class="pagelarger nrnodisp">2</a></nav>';

で、当然のこと、何かを親要素としてこれをこのまま append という具合にはできないわけで。
たぶん、引数で与えられたものは、オブジェクトじゃないよ!というお叱りを受けてしまう。
それなら、と、その前に DOM オブジェクトにしておけばいい。そこで DOMParser のご登場となる。
カギは5行目の parser.parseFromString 、引数の詳細は -> 「MDN Web Docs DOMParser」をご覧あれ。

const parser = new DOMParser();

const pager = '<nav class="pagenavilist"><span class="pages">1/7</span><span class="current">1</span><a href="http://localhost/wp/?paged=2" class="pagelarger nrnodisp">2</a></nav>';

const tohtml = parser.parseFromString( pager, 'text/html' ),
	dmpager = tohtml.getElementsByTagName( 'nav' );

const content = document.getElementById( 'content' );

content.append( dmpager[0] );

まぁ、私的には const での初期化の行をこんなに分けたりはせず、全部ひとまとめにしてしまう。

ところで、これは別に DOMParser を使わずとも普通に出来る。
と、いうか、実を言うと、その存在を知らずに自分自身はじめはこちらでやっていた。たぶん、こういうものがあるんじゃないかな~、という気はしていたのだけれど。調べてるよりやっちゃったほうが早いし、と思いつつね。でも、知ってみるとこれはたぶん DOMParser の方が高速に動く。

で、話をもどして、何か要素を一つ作っておいて、innerHTML でその要素の子要素にしてしまえばいい。

const topdiv= document.createElement( 'div' );

const pager = '<nav class="pagenavilist"><span class="pages">1/7</span><span class="current">1</span><a href="http://localhost/wp/?paged=2" class="pagelarger nrnodisp">2</a></nav>';

topdiv.innerHTML = pager;

const toppager = topdiv.getElementsByTagName( 'nav' );

const content = document.getElementById( 'content' );

content.append( toppager[0] );

わざわざ最外殻の div を取る必要もないかもしれないが、DOM の階層は浅いのが理想的。

Leave a Reply!

JavaScript is necessary to send a comment.
You can edit and delete your comment if you input a edit key.
Edit key is necessary for attesting you when you edit and delete it.
The tag of HTML cannot be used in comment.
When you comment for the first time, it is displayed after the approval of the administrator.
Because I cannot speak English so much, it takes time to answer.
Required fields are marked *.

※Please enter more than 5 characters only alphabets.
※Edit or delete are possible for 2000 days after approval.

*

♠Simplistic Comment User Editable v4.0

♠When visitors leave comments on the site this site collect the data shown in the comments form, and also the visitor’s IP address and browser user agent string to help spam detection.
♠This site does not use cookie when visitors leave comments and commenter edit comment.
♠This site uses Akismet to reduce spam. Learn how your comment data is processed.

Comments feed

Trackback URL : https://strix.main.jp/wp-trackback.php?p=167619

Sanbanse Funabashi

Top

スクロールさせるか画像をクリックすると元に戻ります。