2016-08-10 5 views
5

HTML属性が存在するかどうかをテストし、属性( "tabindex")プロパティを持つ値を取得しようとしています。しかし、私は以下のエラーが発生しています:HTML属性が存在するかどうかをテストして値を取得する

Unable to get property 'hasAttribute' of undefined or null reference

私はjGridとjQueryを使用しています。属性が存在する場合は、その特定のtdの値を取得しようとしています。

<tr class="jqgrow ui-row-ltr ui-widget-content myAltRowClassEven ui-state-highlight" tabindex="0" id="2" role="row" aria-selected="true"> 
    <td aria-describedby="jqGrid11_cname" title=" TESTTHIS" class="zeroBorderRight" style="text-align: left; height: 20px;" role="gridcell"> 
     TESTTHIS 
    </td> 
</tr> 
+1

どのようにhtml要素を選択していますか? 「未定義のxxxを入手できません」と表示された場合、要素への参照に問題がある可能性があります。 – Hodrobond

+0

テストのコードを投稿してもよろしいですか?コードを見ることができれば、エラーの内容を簡単に伝えることができます。 –

+1

"jqgrid"を質問のタグとして追加しました。問題をより明確に定式化すると、(コールバック内で)何らかの属性の存在をテストする必要がある場合に役立ちます。 JavaScriptコードを含めると、多くのことがクリアされます。 – Oleg

答えて

2

tabindex属性を持つ要素をfilteroutするjQueryのhas attribute selectorを使用します。

は、以下のコードを参照してください。

var text = $('td[tabindex]').text(); 
//--------------^^^^^^^^^^-------------------- 
+0

こんにちは@Pranav。あなたの提案に感謝します。しかし、問題は、テーブルがループ内にあり、tabindexでtdがたくさんあることです。申し訳ありませんが、ループに入っていることを忘れてしまいました。 – user3213490

+0

@ user3213490 '[tabindex]'はフィルタリングするのに役立ちます。たとえば: '$( '。yourclass [tabindex]')' –

3

この試してみてください:あなたはtabindex属性の値を取得したい場合は、あなたが行うことができます属性

$("#item").attr("tabindex") 
+0

これはうまくいきました。あなたのソリューションのすべてに感謝します。 – user3213490

0

jqueryのない溶液、ES6

var hasAttr = [...document.getElementById('#blah').attributes] 
    .map(a => a.name) 
    .indexOf(ATTRIBUTE) > -1; 
1

を:

$(function() { 
 
    $('table tbody tr[tabindex]').each(function (i, e) { 
 
    var tabindex = e.getAttribute('tabindex'); 
 
    console.log('tabindex=' + tabindex + ' Row text: ' + e.textContent); 
 
    }); 
 
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> 
 

 
<table> 
 
    <tbody> 
 
    <tr class="jqgrow ui-row-ltr ui-widget-content myAltRowClassEven ui-state-highlight" id="1" role="row" 
 
     aria-selected="true"> 
 
     <td aria-describedby="jqGrid11_cname" title=" TESTTHIS" class="zeroBorderRight" 
 
      style="text-align: left; height: 20px;" role="gridcell"> TESTTHIS 
 
     </td> 
 
    </tr> 
 
    <tr class="jqgrow ui-row-ltr ui-widget-content myAltRowClassEven ui-state-highlight" tabindex="0" id="2" role="row" 
 
     aria-selected="true"> 
 
     <td aria-describedby="jqGrid11_cname" title=" TESTTHIS" class="zeroBorderRight" 
 
      style="text-align: left; height: 20px;" role="gridcell"> TESTTHIS 
 
     </td> 
 
    </tr> 
 
    <tr class="jqgrow ui-row-ltr ui-widget-content myAltRowClassEven ui-state-highlight" tabindex="2" id="3" role="row" 
 
     aria-selected="true"> 
 
     <td aria-describedby="jqGrid11_cname" title=" TESTTHIS" class="zeroBorderRight" 
 
      style="text-align: left; height: 20px;" role="gridcell"> TESTTHIS 
 
     </td> 
 
    </tr> 
 
    </tbody> 
 
</table>