2017-02-28 4 views
-1

配列があり、配列内のイメージタグのインデックスを返すためにjavascriptを使用して関数を作成しようとしています。私のコードでimgpがタグであるところ、すべて同じクラスを共有しています。配列内のイメージタグのインデックス番号を取得

const getClass = document.querySelectorAll('.grp1') 
const intoArray = Array.from(getClass) 
console.log(intoArray) ====> [img.headPic.grp1,p.grp1,p.grp1] 

私はindexOf('img')を使用してみましたが、それは、それが配列でそれを見つけることができなかったという意味、-1を返します。

+0

あなたの配列項目は 'img.headPic.grp1' ではないのimgです。 indexOf( 'img.headPic.grp1')を試してください。 –

+0

文字列をindexOfに渡していますが、変数 'img'を渡したいとします。代わりに 'indexOf(img)'を使用してください – baao

+0

indexOf( 'img.headPic.grp1')はその特定の値とタイプに対してのみ動作します。値が恣意的に変化するかどうか、型が常に文字列かどうか、またはそれがオブジェクトか何かなのかを明確にしてください。 – atomCode

答えて

0

配列全体を繰り返し処理して、各要素のノード名を調べることができます。例えば。

アレイ全体を繰り返し処理し、必要なデータを取得する方法はすべてあります。 Array#findIndexが利用可能な場合、その代わりに使用します。

var index = intoArray.findIndex(function(element) { return element.nodeName === 'IMG'; }); 

あなたはまた、直接の要素を照会し、indexOf使用することができます

var img = document.querySelector('img.grp1'); 
var index = Array.from(document.querySelectorAll('.grp1')).indexOf(img); 
0

あなたは現在の文字列ではなくのために探しているがインスタンス。 .indexOf('img')は実際の画像要素ではなく文字列"img"を検索しているため機能しません。 document.querySelector('.headPic')

イメージインスタンスを配置すると、実際にindexOfを使用してインスタンスを検索できます。 配列が実際に配列の場合のみ!

ドキュメント照会関数(document.getElementsByName、document.querySelectorAllなど)のほとんどは、NodeListとして知られているものを返します。配列のような機能の大部分は、そのような種類のオブジェクト(ループなど)で実装されますが、それらのすべてではありません。 indexOf(filter、forEach、map)を使用できるようにするには、まずオブジェクトが配列に変換されていることを確認する必要があります。

デイヴィッドウォルシュ詳細へようこそhere

var nodesArray = Array.prototype.slice.call(document.querySelectorAll("div")) 

上記のコードの結果は、QSAによって返されたすべてのノードを含む真Arrayオブジェクトです。あなたも、この代替を使用してコードを短くすることができます:

var nodesArray = [].slice.call(document.querySelectorAll("div")); 

var el = document.querySelectorAll('.grp1'); 
 
var img = document.querySelector('.headPic'); 
 
// el.indexOf(img); 
 
// this can't work right now because the object is still a NodeList at that point 
 
var el_array = Array.prototype.slice.call(el); 
 
var num = document.querySelector('.numIndex'); 
 

 
num.innerHTML = el_array.indexOf(img);
<p class="grp1">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus animi.</p> 
 
<p class="grp1">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus animi.</p> 
 
<img class="headPic grp1" src="http://placehold.it/200/300"> 
 
<p class="grp1">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus animi.</p> 
 
<p>Index of the image is <span class="numIndex"></span></p>

+0

OPは既にリストを配列に変換しています。最新のアップデートを参照してください。 –

関連する問題