Low Quality

Change anchor text using JavaScript

HTML example:

<div id="video-quality" style=""> <a class="low bttn" href=""> <span>Low Quality</span> </a> </div> 

Hi, I am trying to use JavaScript to target an anchor tag and change its current Low Quality text to High Quality.

I don't know JavaScript very well, but this is what I came up with. But it obviously does not work:

 var vid_id=document.getElementById('video-quality'); var anchor=vid_id.getElementsByTagName('a'); anchor.innerHTML="High Quality"; 
+4
source share
4 answers

Assuming there is only one anchor in the video-quality div , you are just around the corner:

 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 (awesome!) A List of matching nodes, in this case the corresponding elements. innerHTML is a property of individual elements, so we need to index in a NodeList to access a specific element. The above code assumes that there is at least one matching element and updates its HTML. If you want to be more protective:

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

This means that there are no suitable anchors.

Please note that this removes the span element, since the span is a descendant of the anchor. If you want to avoid this, simply find the span elements as descendants of the anchor, just like you looked for anchors in a div .


FWIW, I would recommend using a reasonable library with a JavaScript browser such as jQuery , YUI , Closure, or any of several others . They provide many features of the utility and smooth out some browser differences. But if you prefer to use the DOM directly, that's good too.

+7
source

If you do not need legacy support (IE7-), you can write:

 document.querySelector('#video-quality a span').innerHTML = 'High Quality'; 

If you need outdated support, I recommend a library like jQuery or similar to make DOM node selection a lot easier with a simple, widespread API.

+4
source

Normal javascript:

 var vid_id = document.getElementById('video-quality'); var span = vid_id.getElementsByTagName('span'); span[0].innerText='High Quality' 

Or you can just use jQuery:

 $('#video-quality span').text('High Quality'); 

hope this helps.

+2
source

Simple is better. Just give the element a span id, and then change it directly.

 <div id="video-quality" style=""> <a class="low bttn" href=""> <span id="quality-setting">Low Quality</span> </a> </div> 

then the script:

 document.getElementById('quality-setting').innerHTML="High Quality"; 
+1
source

Source: https://habr.com/ru/post/1444686/


All Articles