.NET には GetElementsByTagName があるのに GetElementById がない
.NET の System.Windows.Forms.HtmlElement クラスには GetElementsByTagName メソッドはあるのに GetElementById メソッドがないのはなぜ?
DHTML(JavaScript) だと両方あるのに。
なので、.NET 用のサブルーチンを作ってみた。こういう実装で合っているのか?
public static HtmlElement GetElementById(HtmlElement target, string tag, string id) { HtmlElementCollection elements = target.GetElementsByTagName(tag); HtmlElement found = null; foreach (HtmlElement element in elements) { if (element.GetAttribute("id") == id) { if (found == null) { found = element; } else { // 重複があった。 throw new KabudaiException(); } } } // null を返すこともある。 return found; }
たとえば
<body> <div id="hoge"></div> </body>
のような場合は、
GetElementById(document.Body, "DIV", "hoge");
のように呼び出す。