Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of a child attribute in javascript?

   <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.

like image 357
Andy Lobel Avatar asked Dec 27 '22 12:12

Andy Lobel


2 Answers

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
like image 100
T.J. Crowder Avatar answered Jan 15 '23 00:01

T.J. Crowder


Use elem.children[0].href.

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

like image 26
SLaks Avatar answered Jan 15 '23 00:01

SLaks