如何在JavaScript中不使用ID获取元素的值

时间:2014-08-12 19:54:07

标签: javascript html jquery-selectors

假设我有以下代码:

<div class="post">
  <h2 itemprop="name">
    <a href="http://www.example.com">The Post Title</a>
  </h2>
<div class="details">
  <span>
    <em class="date">Jul 17, 2014  </em>
  </span>
  <span>
    Category:  
    <a href="/category/staff-profile/">Staff Profile</a> 
  </span>
</div>

如何在不更改页面上的HTML的情况下使用JavaScript获取“帖子标题”和“员工档案”的值?即我不能使用getElementbyID作为例子。如果必须,我可以使用jQuery,但如果可能的话,我宁愿不这样做。

4 个答案:

答案 0 :(得分:4)

您可以使用返回数组的getElementsByTagName来获取这些值

document.getElementsByTagName("a")[0].innerHTML // returns The Post Title
document.getElementsByTagName("a")[1].innerHTML // returns Staff Profile

如果这些链接是第一个,你可以使用索引0和1,否则你应该寻找正确的索引

更新

另一种可能很简单的方法是使用类post

在div中选择这些链接
var links = document.getElementsByClassName("post")[index].getElementsByTagName("a");
links[0].innerHTML; // returns The Post Title
links[1].innerHTML; // returns Staff Profile

如果类post的div的索引没有改变,那么这个解决方案将是最好的

答案 1 :(得分:3)

对于基于jQuery的表达式,您可以使用:

$('a').map(function() {
    return [this.href, this.textContent];
}).get();

应返回:

[ [ 'http://www.example.com', 'The Post Title' ],
  [ 'http://sitename/category/staff-profile/', 'Staff Profile' ] ]

如果您特别需要原始相对网址而不是规范化的完整网址,请使用this.getAttribute(href)代替this.href

对于纯粹的(ES5)等价物:

[].map.call(document.getElementsByTagName('a'), function (el) {
    return [el.href, el.textContent];
});

不支持W3C标准.textContent属性的较旧浏览器可能需要.innerText属性,例如:

return [el.href, el.textContent || el.innerText];

答案 2 :(得分:2)

你可以这样做:

var posts = document.querySelector('.post');

for (var i = 0; i < posts.length; i++) {
    var links = document.querySelectorAll('a');
    var title = links[0].innerText || links[0].textContent;
    var profile = links[1].innerText || links[1].textContent;
}

答案 3 :(得分:1)

如果您使用的是更现代的浏览器,则可以使用document.querySelectorAll(),它采用CSS样式选择器语法。

var aList = document.querySelectorAll('.post a');
for (var i = 0; i < aList.length; ++i) {
  alert(aList[i].innerHTML);
}

JSFiddle

我用过&#39; .post a&#39;而不只是&#39; a&#39;因为我认为你的页面可能有其他的&#39; a&#39;你不一定想要的标签。

相关问题