获取元素ID - JavaScript

时间:2017-03-30 13:31:01

标签: javascript jquery html

我知道data-id元素中的li,但现在我想要id元素的li值。我怎么能得到这个?尝试:

 var id = $('li[data-id="KnSubject[StId]"]').id;
 console.log(id); // UNDEFINED

Html代码:

<li role="treeitem" data-jstree="{&quot;icon&quot; : &quot;glyphicon glyphicon-pencil&quot;}" data-id="KnSubject[StId]" data-values="null" aria-selected="true" aria-level="3" aria-labelledby="j1_4_anchor" id="j1_4" class="jstree-node  jstree-leaf"><i class="jstree-icon jstree-ocl" role="presentation"></i><a class="jstree-anchor jstree-clicked" href="#" tabindex="-1" id="j1_4_anchor"><i class="jstree-icon jstree-themeicon glyphicon glyphicon-pencil jstree-themeicon-custom" role="presentation"></i>Type dossieritem (StId)</a></li>

3 个答案:

答案 0 :(得分:4)

var id = $('li[data-id="KnSubject[StId]"]').attr('id');
console.log(id);

答案 1 :(得分:1)

使用attr功能。

var elem = $('li[data-id="KnSubject[StId]"]');
console.log(elem.attr('id'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li role="treeitem" data-jstree="{&quot;icon&quot; : &quot;glyphicon glyphicon-pencil&quot;}" data-id="KnSubject[StId]" data-values="null" aria-selected="true" aria-level="3" aria-labelledby="j1_4_anchor" id="j1_4" class="jstree-node  jstree-leaf"><i class="jstree-icon jstree-ocl" role="presentation"></i><a class="jstree-anchor jstree-clicked" href="#" tabindex="-1" id="j1_4_anchor"><i class="jstree-icon jstree-themeicon glyphicon glyphicon-pencil jstree-themeicon-custom" role="presentation"></i>Type dossieritem (StId)</a></li>

答案 2 :(得分:0)

出于完整性原因:

$('li[data-id="KnSubject[StId]"]').get(0).id

.get(0)检索原始JS DOM元素。