LoginSignup
1
1

More than 5 years have passed since last update.

D3.jsで子要素ごとコピーして追加する

Last updated at Posted at 2016-12-21

D3.js(ver4)を使っており、Selection(D3.jsでラッパーしたDOM要素)をコピーしたいと思っていたところ、「D3.jsで要素をコピーして追加する」の記事が参考になりました。

上記の処理を少し拡張することで子要素も含めてSelectionをコピーする事ができます。(jQueryだと要素コピーするためのclone関数があるけど、D3.jsには無さげ...?)

Selectionをコピーする関数
// 第一引数はコピーの対象Selection、第二引数はコピーの追加先Selection
function copySelection( $target, $to ) {
    let node = $target.node();
    let {nodeName, attributes, children} = node;
    let $copy = $to.append(nodeName);

    Object.keys(attributes).forEach((key) => {
        $copy.attr(attributes[key].name, attributes[key].value);
    });
    $copy.html($target.html());

    return $copy;
}
関数を実行
let $copy = copySelection( d3.select('g'), d3.select('svg') );

一応、実際に動くものもこちらに用意しました。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1