Changing anchor text with JavaScript

html, javascript

Solution

Assuming the `video-quality` `div` will only ever have one anchor in it, you're not far off:

var vid_id=document.getElementById('video-quality');
var anchor=vid_id.getElementsByTagName('a');
anchor[0].innerHTML="High Quality";
//    ^^^-- change here

(There's a shorter way if you don't need to support IE7 and earlier, see David's answer for more.)

The key was in the name `getElementsByTagName` (note the plural). It returns a `NodeList`, not an element. A `NodeList` is (shockingly!) a list of matching nodes, in this case matching elements. `innerHTML` is a property of individual elements, so we have to index into the `NodeList` to access a specific element. The code above assumes there is at least one matching element, and updates its HTML. If you want to be more defensive:

var vid_id=document.getElementById('video-quality');
var anchors=vid_id.getElementsByTagName('a');
if (anchors[0]) {
    anchors[0].innerHTML="High Quality";
}

That allows for the possibility there are no matching anchors.

Note that by doing this, you're removing the `span` element, since the `span` is a descendant of the anchor. If you wanted to avoid that, just look for `span` elements as descendants of the anchor, exactly as you've looked for anchors in the `div`.

FWIW, I'd recommend using a reasonable JavaScript browser-focussed library like jQuery, YUI, Closure, or any of several others. They provide a lot of utility functionality, and smooth over some browser differences. But if you prefer using the DOM directly, that's fine too.

Problem

Example HTML: ``` <div id="video-quality" style=""> <a class="low bttn" href=""> <span>Low Quality</span> </a> </div> ``` Hey im trying to use JavaScript to target an anchor tag and change it's current text of "Low Quality" to "High Quality". I don't really know JavaScript very well, but this is what I have come up with. But it's obviously not working: ``` var vid_id=document.getElementById('video-quality'); var anchor=vid_id.getElementsByTagName('a'); anchor.innerHTML="High Quality"; ```

Original source