获取li标签内的锚值 [英] Getting an anchor value which is inside a li tag

查看:105
本文介绍了获取li标签内的锚值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

<li class="email">
    <a href="mailto:abc@gmail.com">abc@gmail.com</a>
</li>

我想获得 abc@gmail.com 使用普通JavaScript

我做了 document.getElementsByTagName(email)给了我上面的内容,但我不知道如何继续。

I though of doing document.getElementsByTagName("email") which gives me the above, but I don't have an idea how to continue.

我已经设法在以下答案的帮助下找到解决方案由用户

I have managed to find a solution with the help of the below answer by a user

var elem = document.querySelectorAll('.email');
var email = elem[0].children[0].innerHTML;


推荐答案

var elems = document.querySelectorAll('.email');
for(var i = 0; i < elems.length; i++) {
    var elem = elems[i];
    console.log(elem.firstElementChild.getAttribute('href').substr(7));
}

演示: http://jsfiddle.net/ThiefMaster/Cx2VY/

然而,文件.querySelectorAll 并非在所有浏览器中都可用。有些还有 document.getElementsByClassName),这对你也有用。但其他浏览器都没有。如果您不想要jQuery等,请考虑添加 Sizzle 。这是使用的选择器引擎jQuery和其他库并消除了处理跨浏览器内容的负担。

However, document.querySelectorAll is not available in all browsers. Some have document.getElementsByClassName) which would also work for you. But other browsers have neither. Consider adding Sizzle if you don't want jQuery etc. It is the selector engine used by jQuery and other libs and takes away the burden of handling the cross-browser stuff from you.

使用 querySelectorAll 或者Sizzle,您可以通过删除 .firstChild 并使用选择器 .email>来使代码更容易。 a 而不是。

When using querySelectorAll or Sizzle, you could make your code even easier by removing .firstChild and using the selector .email > a instead.

这篇关于获取li标签内的锚值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆