2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HTML: DOM取得のなまくら術

Last updated at Posted at 2024-03-28

対応できるかどうかはBrowser次第。いつの間にやら非推奨になってしまったり、廃れていったりする可能性もあります

関数 なまくら術
document.getElementById,
document.querySelector
id属性値を直指し
document.getElementsByTagName("*"),
document.querySelectorAll("*")
document.all
document.getElementsByTagName("form") document.forms
document.querySelectorAll("a[href]") document.links
document.querySelectorAll("a[name]") document.anchors
document.getElementsByTagName("html")[0] document.children[0], document.lastChild, document.documentElement
document.getElementsByTagName("head")[0] document.head
document.getElementsByTagName("body")[0] document.body
document.getElementsByTagName("script") document.scripts
document.getElementsByTagName("img") document.images
document.getElementsByTagName("embed") document.embeds, document.plugins
document.getElementsByTagName("iframe")[0].contentWindow frames[0]

例題

<form id=f><input id=i></form>

上記のようなhtmlでform要素やinput要素を取得する場合、以下のようにできます

//form
a=document.forms[0];
b=document.forms.f;
c=f;
//input
A=document.forms[0].i;
B=document.forms.f.i;
C=i;

framesfor ofで参照できません。for inでは参照可能ですが、iframe以外のobjectも参照しまくるので不便です。frames.length分だけ普通のfor loopで巡回すると良いです。

let a=document.getElementsByTagName("iframe");
console.log(a.length==frames.length);
console.log(a[0].contentWindow==frames[0]);

let c=0;
for(let b of a)console.log(c++);
for(;c;)console.log(frames[--c]);
for(let b in frames)console.log(b);// iframe以外も参照
for(let b of frames)console.log(c++);// error

後書き

まあ当たり前尽くしの事ではありますが、過剰なまでの関数連呼やjqueryの無駄遣いをちらほら見掛けるのもまた事実

2
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?