为了账号安全,请及时绑定邮箱和手机立即绑定

使用 java 脚本或 jquery 提取 <li> 标记内的文本

使用 java 脚本或 jquery 提取 <li> 标记内的文本

精慕HU 2022-10-13 09:47:46
var array1[] ;//i want to store text inside href in a array like this// [cat,dog,cow,hen,elephant] , how can I do that?<div class="ABCD"><h2 class="AB">Tags</h2><ul> <li><a href="/example">cat</a></li> <li><a href="/example2">dog</a></li> <li><a href="/example3">cow</a></li> <li><a href="/example4">hen</a></li> <li><a href="/example5">elephant</a></li></ul></div>我想使用 javascript 让 cat,dog,cow,hen,elephant 排列动物 []。我怎样才能把它们放到一个数组中?请帮忙
查看完整描述

3 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超3个赞

请参阅下面的您正在寻找的要求


let allLinks = document.querySelectorAll("div.ABCD  li > a")


let allLinksarray = Array.from(allLinks).map(linkElem => linkElem.innerHTML)


console.log(allLinksarray)

<div class="ABCD">

  <h2 class="AB">Tags</h2>

  <ul>

    <li><a href="/example">cat</a></li>

    <li><a href="/example2">dog</a></li>

    <li><a href="/example3">cow</a></li>

    <li><a href="/example4">hen</a></li>

    <li><a href="/example5">elephant</a></li>

  </ul>

</div>


查看完整回答
反对 回复 2022-10-13
?
手掌心

TA贡献1942条经验 获得超3个赞

假设您是初学者(对不起,如果我在这里判断错误),这里有一个详细的解释:( 链接)


let list = document.getElementById('list').children // Add the ID 'list' to the ul element, and declare it here.

let myArray = [] // Empty array for the results to go too

for (let item in list) { // For every item in the list...

    if (list[item].children) { // Take the element with the index of 'item' from the list, and find it's children (a tag)

  myArray.push(list[item].children[0].innerHTML) // Add the innerHTML (text) to a new item on the array

  }

}


console.log(myArray) // Log the Array

这里还有很多其他的解决方案也可以


查看完整回答
反对 回复 2022-10-13
?
偶然的你

TA贡献1841条经验 获得超3个赞

使用 jQUERY


const li  = $('.ABCD').find('li > a');

const resultArray = Array.from(li).map(a => a.innerHTML)

console.log(resultArray);


查看完整回答
反对 回复 2022-10-13
  • 3 回答
  • 0 关注
  • 241 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号