Reputation: 79
I am use DOM to get multiple class names and pass a function(with_value) to access individual elements. However I get a Uncaught TypeError cannot read propperty 'innerHTML' of undefined. Code is:
<script>
var token = 1;
var x = document.getElementsByName("commpare_name");
var y = document.getElementsByName("compare_image");
function add_compare(num)
{ num=0;
var a = x[num].innerHTML.toUpperCase();
alert(a);
document.getElementById('name1').innerHTML = a;
document.getElementById('name1').title = a
document.getElementById('pics1').src = x[num].src;
a = document.getElementById('view-details0').action;
}
</script>
<span id="compare_name" name="compare_name" >no1</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare(1)">
</form>
<span id="compare_name" name="compare_name" >no1</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare(2)">
</form>
edit:
<a class="description" id="name1" href="" target="_blank" title="ADD TO COMPARE" ><span>ADD TO COMPARE</span></a>
the innerHTML and thee href of this needs to change
Upvotes: 0
Views: 4930
Reputation: 830
var x = document.getElementsByName("commpare_name");
should be..
var x = document.getElementsByName("compare_name"); //Typo in **compare_name**
Upvotes: 0
Reputation: 19475
The actual problem is that you execute your JavaScript before the DOM Content is loaded. Wrap your JS in
window.addEventListener('DOMContentLoaded',function(){
…
});
or put your <script>
at the bottom of your <body>
.
When you execute
var x = document.getElementsByName("commpare_name");
you get an empty NodeList
because no elements with such a name exist yet. When you try to access x[num]
which is x[0]
that property 0
doesn’t exist, thus it results in undefined
.
var a = x[num].innerHTML.toUpperCase();
Afterwards .innerHTML
is being read from undefined
which is impossible.
Update: I didn’t realize that the name
was misspelt as well as pointed out by Vivek Gupta. You obviously have to change that. If your <script>
actually is above that HTML then you still have to change the script position or wrap it as described above.
Upvotes: 1
Reputation: 1055
You are giving wrong name in script
commpare_name - > compare_name
Upvotes: 3