<div class="menu_item_variant" id="date" onmouseover="mouseIn(this.id)" onmouseout="mouseOut(this.id)">
<a href="dating-advice.html">Dating Coaching & 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 & Advice</a>
</div>
hi, could some one help me get the value of href
using document.getElementById("date")
etc. thanks ! Andy.
4 Answers
Reset to default 10You 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 & Advice</a>
</div>