Bilal Shafi
Bilal Shafi

Reputation: 166

onclick on a hyperlink not running javascript in blogger

My Javascript

<script type='text/javascript'>
 //<![CDATA[
function showAnswer()
{
  alert('Answer');
  var els = document.getElementsByClassName('answer');
if (els.style.display != 'inline')
    els.style.display = 'inline';
} 
}

     //]]>
</script>

Where answer is a class name on page for p tag which is initially hidden by the following code:

 .answer { display:none; }

This is code for calling showAnswer which is not working...

 <div class='show_hide_answers'>
        <a href='#' onclick='showAnswer();'>Show Answer</a>
 </div>

Clicking on Show answer does nothing. Even it is not showing alert means javascript is not running. Please help me solve this problem. See this page for more details (this is the code for this page)

http://www.technodoze.com/2012/09/the-idea-that-light-is-em-wave-was.html

Thanks in advance if you could help me plz...

Note: I have tried all these:

<a href='#' onclick='showAnswer()'>Show Answer</a>

<a href='#' onclick='javascript:showAnswer();'>Show Answer</a>

<a href='#' onclick='javascript:return showAnswer();'>Show Answer</a>

No one is working.

Upvotes: 0

Views: 666

Answers (2)

Martin Trenker
Martin Trenker

Reputation: 167

if you debug javascript, please use your console, it says "Uncaught SyntaxError: Unexpected token }". there is a { missing after the if.

also getElementsByClassName does not return a single element but a set of elements (notice the getElement_s_)

Upvotes: 0

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91299

getElementsByClassName returns a NodeList instead of a single Node. Thus, you need to iterate over the resulting NodeList:

var els = document.getElementsByClassName('answer');
for (var i = 0; i < els.length; i++) {
  var el = eles[i];
  if (el.style.display != 'inline') {
    el.style.display = 'inline';
  }
} 

Upvotes: 1

Related Questions