我正在尝试获取放置在 html 页面上的特定锚标记的href 值。
html标签结构
<a rel="nofollow" title="some title" href="http://www.this-is-what-i-need.com/just-this.html"><span><em class="buttonGo"></em>Go to this page</span></a>
Run Code Online (Sandbox Code Playgroud)
如何使用buttonGo类名从上面的锚标记获取href值?
小智 6
一行简单的 Javascript 就能满足您的需求:
\n\nvar href = document.getElementsByClassName("buttonGo")[0].parentNode.parentNode.href;\nRun Code Online (Sandbox Code Playgroud)\n\n但是,如果您不确定需要使用多少次parentNode,则必须使用循环:
var anchor = document.getElementsByClassName("buttonGo")[0];\ndo{\nanchor = anchor.parentNode;\n} while(anchor.nodeName.toLowerCase() != "a");\nvar href = anchor.href;\nRun Code Online (Sandbox Code Playgroud)\n\n演示:解决方案一(由Milche Patern创建)和解决方案二
\n