Skip to content

Instantly share code, notes, and snippets.

@think49
Last active June 21, 2017 01:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save think49/4cd2cfc82f308c7b5d696dc2a50af3d4 to your computer and use it in GitHub Desktop.
Save think49/4cd2cfc82f308c7b5d696dc2a50af3d4 to your computer and use it in GitHub Desktop.
swap-node.js: 2つのノードの位置を入れ替えます

swap-node.js

概要

2つのノードの位置を入れ替えます。

制約

内部的に Node#replaceChild, Node#appendChild, Node#insertBefore を使用している関係上、下記制約があります。

  • 2つのノード間に親子関係、祖先関係が成立する場合には入れ替えられません。
  • 2つのノードはそれぞれ親ノードが存在しなければなりません。従って、AttrDocumentDocumentFragmentEntityNotation ノードを入れ替えることは出来ません。

使い方

第一引数、第二引数で指定したノードの位置を入れ替えます。

<p id="p1">paragraph1</p>
<p id="p2">paragraph2</p>
<script>
swapNode(document.getElementById('p1'), document.getElementById('p2'));
</script>

対象は要素ノードである必要はなく、例えば、テキストノードと要素ノードを入れ替える事も可能です。

<p id="p3">text<span>span1</span><span>span2</span></p>
<script>
var p3 = document.getElementById('p3');
swapNode(p3.firstChild, p3.lastChild);
</script>

参考リンク

/**
* swap-node.js
* Swap the positions of the two nodes.
*
* @version 1.0.2
* @author think49
* @url https://gist.github.com/think49/4cd2cfc82f308c7b5d696dc2a50af3d4
* @license http://www.opensource.org/licenses/mit-license.php (The MIT License)
*/
var swapNode = (function (Object) {
'use strict';
function isNode (node) {
return Object(node) === node && typeof node.nodeType === 'number';
}
return function swapNode (node1, node2) {
if (!isNode(node1)) {
throw new TypeError('parameter 1 is not of type \'Node\'');
}
if (!isNode(node2)) {
throw new TypeError('parameter 2 is not of type \'Node\'');
}
if (node1 === node2) {
return;
}
var parentNode1 = node1.parentNode,
parentNode2 = node2.parentNode;
if (!parentNode1) {
throw new TypeError('parentNode of parameter 1 is ' + parentNode1);
}
if (!parentNode2) {
throw new TypeError('parentNode of parameter 2 is ' + parentNode2);
}
var nextNode1 = node1.nextSibling;
if (nextNode1 === node2) {
parentNode1.insertBefore(node2, node1);
} else {
parentNode2.replaceChild(node1, node2);
nextNode1 ? parentNode1.insertBefore(node2, nextNode1) : parentNode1.appendChild(node2);
}
}
}(Object));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment