如何获得href值?

时间:2014-02-05 10:47:32

标签: javascript href

为了简单起见,我目前正在使用javascript。如何获取href值并将其存储在javascript变量中。我需要提取每个课程部分的所有属性href值以及每个部分中的每个项目。

<ul class="curriculum-items-list">
 <li class="curriculum-section-container ng-scope">
  <ul>
   <li class="curriculum-item-container ng-scope">
    <a href="http://www.mywebsite.com/videoSec1_1.mp4">
   </li>
   <li class="curriculum-item-container ng-scope">
    <a href="http://www.mywebsite.com/videoSec1_2.mp4">
   </li>       
  </ul>
 </li>
 <li class="curriculum-section-container ng-scope">
  <ul>
   <li class="curriculum-item-container ng-scope">
    <a href="http://www.mywebsite.com/videoSec2_1.mp4">
   </li>
   <li class="curriculum-item-container ng-scope">
    <a href="http://www.mywebsite.com/videoSec2_2.mp4">
   </li>       
  </ul>
 </li>
</ul>

渴望结果

http://www.mywebsite.com/videoSec1_1.mp4
http://www.mywebsite.com/videoSec1_2.mp4
http://www.mywebsite.com/videoSec2_1.mp4
http://www.mywebsite.com/videoSec2_2.mp4

3 个答案:

答案 0 :(得分:3)

您可以使用querySelectorAll来引用a元素,然后使用Array.prototype.map将相关数据提取到数组中:

var hrefs = [].map.call(document.querySelectorAll(".curriculum-item-container a"), function (elem) {
    return elem.href; 
});

这是working example

答案 1 :(得分:0)

var hrefs = [];
$(".curriculum-item-container a").each(function (i, a) {
    hrefs.push(a.getAttribute("href"));
});

答案 2 :(得分:0)

另一种使用 querySelectorAll 获取所有 href 的方法。

let hrefs = [];

document.querySelectorAll('.curriculum-item-container a').forEach(a => {
  hrefs.push(a.href);
})