IE 8以降およびほとんどの新しいブラウザでは、
document.querySelector
およびdocument.querySelectorAll
を使用してください。 これらの方法は、CSSのようにセレクタにより任意の要素にアクセスすることができ可能:)それらの間
var e = document.querySelectorAll(".myClass"); //
差が最初に一致した要素のコレクションを取得マッチ要素、第二の方法の最初の要素を取得することです。
デモ:http://jsfiddle.net/f9cHr/要素の色を変更するには、文書をクリックしてください。
そして今:
getElementsByClassName = function(className , ctx ) {
var context = ctx ? (typeof ctx =="string" ? document.querySelector(ctx) : ctx): document;
return context.querySelectorAll && context.querySelectorAll("." + className)
};
querySelector`s機能が
if(document.querySelector && document.querySelectorAll) {
//getElementsByClassName = function from above here
} else {
//getElementsByClassName = function you are using here
}
利用存在しているときは、この機能を使用することができます。また、
var myClassInnerMyId =
getElementsByClassName("myClass" , document.getElementById("myId"));
// = document.querySelectorAll("#myId .myClass");
someClassesInnerOtherId = getElementsByClassName("myClass1,myClass2" , "#otherId");
// = document.querySelectorAll("#otherId myClass1, #otherId myClass2");
だけでなく、あなたが拡張している(あなたがやるべきでない)、あなたはまた 'Array'なく' NodeList'を再調整しているネイティブオブジェクト/ 'HTMLCollection'です。 – Pavlo
ノードリストはオブジェクトであり、オブジェクトは配列です。 –
'Array'は' NodeList'と異なり、 'item()'メソッドを持っていません。また、オブジェクトの* all *に対する列挙可能な 'getElementByClassName'メソッドを作成したことは分かりますか?私は同じ決断を下す別の答えを見ない。 – Pavlo