从无序列表<ul>获取<li>的属性值

时间:2019-01-25 19:32:43

标签: javascript jquery

我想在类aria-selected="true"的范围内显示属性为categoryID的“ li”的ID值

我的代码如下:

var category_Tree = $('#categorycontainer').find("[aria-selected='true']");
var selected_category = category_Tree.attr("id"); 

$('.categoryID').html(selected_category);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="categorycontainer">
   <ul>
      <li url="http://www.google.com" id="1" aria-selected="true">Google</li>
      <li url="http://www.yahoo.com" id="2" aria-selected="false">Yahoo</li>
      <li url="http://www.bing.com" id="3" aria-selected="false">Bing</li>
      <li url="http://www.facebook.com" id="4" aria-selected="false">Facebook</li>
      <li url="http://www.amazon.com" id="5" aria-selected="false">Amazon</li>
    </ul>
</div>
<span class="categoryID"><span>

但是它不起作用,请提供任何帮助

2 个答案:

答案 0 :(得分:-2)

您可以使用 css属性选择器获取所有具有属性aria-selected='true'的元素。选择li元素后,您可以通过id属性获取其id。

let li = document.querySelectorAll('#categorycontainer>ul>li[aria-selected=true]');
let categoryID = document.querySelector('.categoryID');
let ids = '';
for(let i of li){
  ids+=(i.id+'\n');
}

categoryID.textContent = ids;
<div id="categorycontainer">
   <ul>
      <li url="http://www.google.com" id="1" aria-selected="true">Google</li>
      <li url="http://www.yahoo.com" id="2" aria-selected="false">Yahoo</li>
      <li url="http://www.bing.com" id="3" aria-selected="true">Bing</li>
      <li url="http://www.facebook.com" id="4" aria-selected="false">Facebook</li>
      <li url="http://www.amazon.com" id="5" aria-selected="false">Amazon</li>
    </ul>
</div>
<span class="categoryID"><span>

答案 1 :(得分:-3)

首先将html转换为数据(在这种情况下为对象数组),然后易于过滤。从这里开始比较容易,请尝试以下操作:

const dataset = [...document.querySelectorAll('ul li')].map(li => ({ id: li.id, selected: li.getAttribute('aria-selected') }))
const data = dataset.find(data => data.selected === 'true')

document.querySelector('.categoryID').textContent = data.id;
<div id="categorycontainer">
  <ul>
      <li url="http://www.google.com" id="1" aria-selected="true">Google</li>
      <li url="http://www.yahoo.com" id="2" aria-selected="false">Yahoo</li>
      <li url="http://www.bing.com" id="3" aria-selected="false">Bing</li>
      <li url="http://www.facebook.com" id="4" aria-selected="false">Facebook</li>
      <li url="http://www.amazon.com" id="5" aria-selected="false">Amazon</li>
  </ul>
</div>
<span class="categoryID"><span>