replaceChildの注意点
2009/09/21(月) 21:16 Javascript親記事へこのエントリーをはてなブックマークに追加

FirefoxはreplaceNodeはないので、replaceChildを使用する。
element.replaceChild - MDC
https://developer.mozilla.org/ja/DOM/element.replaceChild

replaceChildはある子ノードを置換するものですが、forなどで回していくときに注意する必要がル。
普段のように上から走査してreplaceChildでノードを書き換えていくと、一つ飛んだ形で置換が行われてしまいます。奇数目のノードしか置換されない。
var iframes = document.getElementsByTagName("iframe");
for (var i = 0; i < iframes.length; i++) {
	if (iframes[i].hasAttribute("src")) {
		var iframeURL = iframes[i].getAttribute("src");
		if (/nicovideo\.jp\/thumb(\/|\?v=)(\w+)/.test(iframeURL)) {
			var mId = RegExp.$2;
			var imgTag = document.createElement("img");
			imgTag.src = "http://niconail.info/" + mId;
			var aNode = document.createElement("a");
			aNode.href = "http://www.nicovideo.jp/watch/" + mId;
			aNode.appendChild(imgTag);
			var parentIframe = iframes[i].parentNode;
			parentIframe.replaceChild(aNode, iframes[i]);
		}
	}
}
あんまり詳しく調べてませんが、これはreplaceChildで書き換えをしたときにノードにずれができてしまうため、望んだ結果が起こらなくなっている。
これを回避するにはforを後ろから回してreplaceChildで置換していくと回避できる。
var iframes = document.getElementsByTagName("iframe");
for (var i = iframes.length - 1; i >= 0; i--) {
	if (iframes[i].hasAttribute("src")) {
		var iframeURL = iframes[i].getAttribute("src");
		if (/nicovideo\.jp\/thumb(\/|\?v=)(\w+)/.test(iframeURL)) {
			var mId = RegExp.$2;
			var imgTag = document.createElement("img");
			imgTag.src = "http://niconail.info/" + mId;
			var aNode = document.createElement("a");
			aNode.href = "http://www.nicovideo.jp/watch/" + mId;
			aNode.appendChild(imgTag);
			var parentIframe = iframes[i].parentNode;
			parentIframe.replaceChild(aNode, iframes[i]);
		}
	}
}

名前:  非公開コメント   

  • TB-URL  http://efcl.info/adiary/010/tb/