次のコードがあるとします。
<div id="container">
<div onclick="func(this)"></div>
...
...
<div onclick="func(this)"></div>
</div>
クリック時func
に取得する関数が必要です:
1. onclick-event が呼び出された div のインデックス。
2. コンテナー内の div の総数。
次のコードがあるとします。
<div id="container">
<div onclick="func(this)"></div>
...
...
<div onclick="func(this)"></div>
</div>
クリック時func
に取得する関数が必要です:
1. onclick-event が呼び出された div のインデックス。
2. コンテナー内の div の総数。
func
receive を最初の引数と仮定するとthis
、以前の兄弟を単純にトラバースし、前に何人来たかを数えてインデックスを計算できます。
合計数を取得するには.children
、親からの数を取得するだけです。
function func(elem) {
var idx = 0;
var total = elem.parentNode.children.length;
// --------v----note the assignment!
while (elem = elem.previousElementSibling) {
idx++;
}
console.log("index:", idx, " of:", total);
}
を持たない古いブラウザをサポートする必要がある場合は、 nodeType が 1 である.previousElementSibling
ことを使用してテストできます。.previousSibling
function func(elem) {
var idx = 0;
var total = elem.parentNode.children.length;
// --------v----note the assignment!
while (elem = elem.previousSibling) {
if (elem.nodeType === 1)
idx++;
}
console.log("index:", idx, " of:", total);
}
これはすべて、コンテナー内にカウントする必要のある要素が他にないことを前提としています。他にもある場合は、カウントから除外する必要があります。
このコードは、必要なことを行います。
function func(el){
// get the list of all element contained by the parent
var list = el.parentElement.children, i;
// get the index of the element
for (i = 0; i<list.length;i++){
if (list[i] == el) break;
}
// logging index and total childrencount to console (F12)
console.log("children total: "+list.length);
console.log("# of element: "+ ++i);
}