最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to get the value of a child attribute in javascript? - Stack Overflow

programmeradmin2浏览0评论
<div class="menu_item_variant" id="date" onmouseover="mouseIn(this.id)" onmouseout="mouseOut(this.id)">
  <a href="dating-advice.html">Dating Coaching &amp; Advice</a>
</div>

hi, could some one help me get the value of href using document.getElementById("date") etc. thanks ! Andy.

<div class="menu_item_variant" id="date" onmouseover="mouseIn(this.id)" onmouseout="mouseOut(this.id)">
  <a href="dating-advice.html">Dating Coaching &amp; Advice</a>
</div>

hi, could some one help me get the value of href using document.getElementById("date") etc. thanks ! Andy.

Share Improve this question edited Apr 19, 2023 at 9:20 djvg 14.3k7 gold badges83 silver badges113 bronze badges asked Oct 31, 2011 at 17:42 Andy LobelAndy Lobel 3,4169 gold badges33 silver badges40 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 10

You can get the "date" element and then loop through its children:

var elm, href;
elm = document.getElementById("date");
for (elm = elm.firstChild; elm; elm = elm.nextSibling) {
    if (elm.nodeName === "A") {
        href = elm.href;
        break;
    }
}

Or actually, I think just about every browser has getElementsByTagName now, so:

var list, href;
list = document.getElementById('date').getElementsByTagName('a');
if (list.length > 0) {
    href = list[0].href;
}

More to explore:

  • DOM2 standard (nearly universally supported)
  • DOM2 HTML (widely supported)
  • DOM3 standard (reasonably supported, but gaps in older browsers, particularly IE)
  • HTML5 DOM interfaces (reasonably supported, as they mostly document DOM2 HTML and things browsers vendors were doing -- but test for gotchas)
  • caniuse.com and quirksmode.org -- handy places for checking which browsers support what technologies

Use elem.children[0].href.

If there may be other children before the <a>, you can write elem.getElementsByTagName('a')[0].href

Using document.getElementById(), you can do this:

document.getElementById("date").getElementsByTagName('a')[0].href

An alternative would be to use CSS selectors in combination with querySelector():

const href = document.querySelector('#date a').href;  // or e.g. '#date [href]'
console.log(href)
<!-- OP's example -->
<div class="menu_item_variant" id="date" onmouseover="mouseIn(this.id)" onmouseout="mouseOut(this.id)">
  <a href="dating-advice.html">Dating Coaching &amp; Advice</a>
</div>

发布评论

评论列表(0)

  1. 暂无评论