LoginSignup
6
2

More than 3 years have passed since last update.

document.createElementより便利

Posted at

忘れない内にメモ
今まで生のJSを使わないと行けない環境でDomをいじくり回したい時は

var id = "hoge";
var text = "Lorem ipsum";
var header = document.createElement("h1");
header.setAttribute("id",id);
header.textContent = text;
// <h1 id="hoge">Lorem ipsum</h1>

とクッソ面倒な事をやってたけど

var id = "hoge";
var text = "Lorem ipsum";
var parser = new DOMParser();
var temp = "<h1 id=" + id + ">" + text + "</h1>";
var doc = parser.parseFromString(temp, "text/html");

と簡潔に書けるらしい。

テンプレートリテラル使えるなら

var id = "hoge";
var text = "Lorem ipsum";
var parser = new DOMParser();
var temp = `<h1 id="${id}">${text}</h1>`;
var doc = parser.parseFromString(temp, "text/html");

めっちゃ楽になる。

6
2
4

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
6
2