Reputation: 1256
I'm trying to change the .innerText
property of the first a
if the selected value of the option
is 1
I'm not seeing any errors in the console and have tried moving my script around to see if that changes anything, but it doesn't. Right now my script is at the end of the body.
why isn't this working?!
demo: http://jsfiddle.net/L2gm9/1/
HTML:
<div id="container">
<ol>
<li><a href="#">This is the first link</a></li>
<li><a href="#">This is the first link</a></li>
<li><a href="#">This is the first link</a></li>
<li><a href="#">This is the first link</a></li>
<li><a href="#">This is the first link</a></li>
<li><a href="#">This is the first link</a></li>
<li><a href="#">This is the first link</a></li>
<li><a href="#">This is the first link</a></li>
</ol>
<select id="numbers">
<option>Select</option>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
</select>
</div>
JS:
(function(){
"use strict";
var select = document.getElementById("element"),
option = select.firstElementChild;
select.addEventListener("onchange", function(){
var div = document.getElementById("hook"),
ol = div.firstElementChild,
li = ol.firstElementChild,
a = li.firstElementChild;
console.log(a);
if(select.children[1].innerText === 1)
a.innerText = "This is the first element";
}, false);
})();
Upvotes: 0
Views: 188
Reputation: 488
Try making an actual javascript function and then adding the onchange attribute to the elements in the html:
function ChangeText() {
var div = document.getElementById("hook"),
ol = div.firstElementChild,
li = ol.firstElementChild,
a = li.firstElementChild;
console.log(a);
if(select.children[1].innerText === 1) {
a.innerText = "This is the first element";
}
}
<select id="numbers" onchange="ChangeText();">...</select>
You might be better off changing the function too, to simplify it, but hopefully this points you in the right direction and solves your immediate problem.
Upvotes: 0
Reputation: 207501
looking at the fiddle and your console, you will see the error Uncaught TypeError: Cannot read property 'firstElementChild' of null
The error is caused by calling the function before the element is loaded on the page.
window.onload = (function(){
"use strict";
var select = document.getElementById("element"),
option = select.firstElementChild;
select.addEventListener("onchange", function(){
var div = document.getElementById("hook"),
ol = div.firstElementChild,
li = ol.firstElementChild,
a = li.firstElementChild;
console.log(a);
if(this.children[0].value === 1)
a.innerHTML = "This is the first element";
}, true);
})(); <-- executes the function and assigns result to unload handler
You want to remove the ()
Now the next issue is you are using addEventListener wrong. You do not use "on" in the event name. Also not all browsers support it.
select.addEventListener("change", function(){
Upvotes: 2