LoginSignup
23
23

More than 5 years have passed since last update.

d3.jsのセレクタとタグ操作

Posted at

はじめに

d3.jsは、セレクタでタグを選択し、操作を行う。
バージョン3.xでのd3の選択、操作をjQuery, javascriptと共にまとめます。

d3.jsセレクタ

d3.jsはselect(単一), selectAll(複数)でタグを選択する。
selectで対象が複数ある場合は、1コ目の要素が選択される。

セレクタ d3 jQuery javascript
タグ指定 d3.select("p"); d3.selectAll("p"); $("p"); document.getElementsByTagName("p");
id指定 d3.select("#id"); $("#id"); document.getElementById("id");
クラス指定 d3.select(".cls"); d3.selectAll(".cls"); $(".cls"); document.getElementsByClassName("cls");

セレクタに続いてセレクタを記述し、さらに要素を特定できる。

d3.select("#id").selectAll("p");

タグ操作

セレクタに続いて記述する。

操作 d3 jQuery javascript
属性取得 selection.attr("id"); selection.attr("id"); selection.getAttribute("id");
属性追加 selection.attr("id", "name"); selection.attr("id", "name"); selection.attrAttribute("id", "name");
属性削除 selection.attr("id", null); selection.removeAttr("id"); selection.removeAttribute("id");
クラス追加 selection.classed("cls", true); selection.addClass("cls"); selection.classList.add("cls");
クラス削除 selection.classed("cls", false); selection.removeClass("cls"); selection.classList.remove("cls");
スタイル取得 selection.style("color"); selection.css("color"); selection.style.color;
スタイル設定 selection.style("color", "blue"); selection.css("color", "blue"); selection.style.color = "blue";
スタイル削除 selection.style("color", null); selection.css("color", ""); selection.style.color = "";
プロパティ値取得 selection.property("checked"); selection.prop("checked"); selection.checked;
プロパティ値設定 selection.property("checked", true); selection.prop("checked", true); selection.checked = true;
html取得 selection.html(); selection.html(); selection.innerHTML;
html設定 selection.html("<p>value</p>"); selection.html("<p>value</p>"); selection.innerHTML = "<p>value</p>";
要素追加 selection.append("p"); selection.append("<p></p>"); selection.appendChild(document.createElement('div'));
要素削除 selection.remove(); selection.remove(); selection.parentNode.removeChild(selection);

dataとenterとexit

dataはセレクタで選択した要素と配列の値(dataset)を関連付ける。
enterは、要素よりdatasetが多い場合、余剰分のdatasetの選択を返す。

var dataset = [...];
selection.data(dataset).enter();

enterの利用例

exitは、datasetより要素が多い場合、余剰分の要素の選択を返す。

var dataset = [...];
selection.data(dataset).exit();

exitの利用例

enterとexitの両方を使ってみました。
enterとexitの利用例

23
23
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
23
23