Skip to content

Instantly share code, notes, and snippets.

@RyoSugimoto
Created October 10, 2014 09:14
Show Gist options
  • Save RyoSugimoto/01b88dbd7c72b32dc04e to your computer and use it in GitHub Desktop.
Save RyoSugimoto/01b88dbd7c72b32dc04e to your computer and use it in GitHub Desktop.
DOM関連のスニペット集。
// 要素の追加
elm.insertAdjacentHTML('afterend', htmlString);
elm.insertAdjacentHTML('beforebegin', htmlString);
parent.appendChild(elm);
parent.insertBefore(el, parent.firstChild);
// トラヴァース
document.querySelectorAll('.my #awesome selector'); // セレクタで指定した要素を、ドキュメント全体から取得
elm.querySelectorAll(selector); // セレクタで指定した要素を、子孫から取得
elm.children; // 子要素
Array.prototype.filter.call(document.querySelectorAll(selector), filterFn); // フィルター
elm.nextElementSibling;
elm.previousElementSibling;
elm.offsetParent || el; // ポジションが設定されている直近の先祖要素を取得
elm.parentNode;
Array.prototype.filter.call(elm.parentNode.children, function (child) {
return child !== elm;
});
// 要素操作
elm.cloneNode(true); // 要素のクローン
elm.getAttribute('tabindex'); // 指定した属性値を取得
elm.setAttribute('tabindex', 3);
elm.parentNode.removeChild(elm);
elm.innerHTML;
elm.outerHTML;
elm.textContent;
elm.offsetHeight; // パディングとボーダーを含む高さ
getComputedStyle(elm)[ruleName]; // スタイルルールを取得
// 調べる
elm !== child && elm.contains(child); // 子に指定した要素を含んでいるか
elm.querySelector(selector) !== null; // 子孫にセレクタで指定した要素があるか
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment