How do I replace innerHTML on page load of a child element?

Viewed 1016

Let's start with I'm not fluent in javascript, but I know a little. I'm on a platform that is running code I can't see on the back-end. That means I can only control so much. For example, there is a tag:

{{ component.quality_switch }}

When the page loads, it swaps that with:

<div class="co-quality-switch" data-behavior="quality_switch">
    <a class="co-quality-switch" href="#" data-behavior="switch-low" style="">
        <i class="co-icon-video-camera"></i>
        watch in high quality
    </a>
</div>

My goal, is to replace the text of the "a" link from "watch in high quality" to "toggle captions". So I experimented and removed the first {{component.quality_switch}} tag and replaced it with the outer div it normally pulls, with an ID added to the div:

<div id="captiontoggle" class="co-quality-switch" data-behavior="quality_switch">
</div>

When the page loaded, it spat back the same as before, with my added id on the div. Progress!

<div id="captiontoggle" class="co-quality-switch" data-behavior="quality_switch">
    <a class="co-quality-switch" href="#" data-behavior="switch-low" style="">
        <i class="co-icon-video-camera"></i>
        watch in high quality
    </a>
</div>

So apparently there is some java on the back-end on the data-behavior="quality_switch" part that is adding all this code. The kicker is, I need all the other things that come with that data-behavior command as that is what swaps my video source to the caption version and back when clicked. So I can't remove it. So my next thought was let's just use JS to change the innerHTML of that "a" link. The innerHTML is:

<i class="co-icon-video-camera"></i>watch in low quality

So if I can just swap that to "toggle captions" I'd be all set. But how can I swap the innerHTML of the "a" link when it doesn't have an ID? I can only assign an ID to it's parent DIV (captiontoggle). I tried adding this script:

<script>
var x = document.getElementById("captiontoggle");
var y = x.getElementsByTagName("a");
y.innerHTML = "test";
</script>

... but it didn't change anything. From my experimenting it looks like maybe I can't do this 2 layers down... Like I could change the innerHTML of captiontoggle, but not it's "a" element.

I'm open to suggestions! Thanks.

1 Answers

You need to use parent reference to get children and change there innerHTML

<script> 
  var x = document.getElementById("captiontoggle"); 
  var y = x.children[0]; 
  y.innerHTML = "test"; 
</script>

Working snippet:

var x = document.getElementById("captiontoggle");
var y = x.children[0];
y.innerHTML = "test";
<div id="captiontoggle" class="co-quality-switch" data-behavior="quality_switch">
  <a class="co-quality-switch" href="#" data-behavior="switch-low" style="">
    <i class="co-icon-video-camera"></i> watch in high quality
  </a>
</div>

Related