0

I have function which has parameter itself and it is working fine

javascript//

<script type="text/javascript">
function $(id){
    document.getElementById(id).style.color="#ff0000"
}
</script>

HTML//

<a href="#" onclick="$('me')">click me</a>
<div id="me">color</div>

Now I change this function a little bit which is not working javascript//

<script type="text/javascript">
function $(id){

    document.getElementById(id)
}

function aaa(){

    $('me').style.color="#ff0000"

}
</script>

HTML//

<a href="#" onclick="aaa()">click me</a>
<div id="me">color</div>

why this function working without return statement

<script type="text/javascript">
function $(id){

    alert(id)
}

function aaa(){

    $('me')

}
</script>
3
  • Your function didn't returned anything the second time; use return statement. Commented Sep 5, 2012 at 6:55
  • But why my updated question is working without return statement Commented Sep 5, 2012 at 7:04
  • Coz in your updated question the actual event is taking place within the function body itself, you aren't using any returns for further use!! Commented Sep 5, 2012 at 7:07

3 Answers 3

1

Your function $(id) does not return anything. It should return the element that you are finding:

<script type="text/javascript">

function $(id){
    return document.getElementById(id);
}

function aaa(){    
    $('me').style.color="#ff0000";
}
</script>

PS. You should probably refrain from naming your function $.

Sign up to request clarification or add additional context in comments.

2 Comments

But why this function will work. <script type="text/javascript"> function $(id){ alert(id) } function aaa(){ $('me') } </script>
@amit because the first function doesn't return anything and the second function does not do anything with the result of the first function. But in your case you are trying to access the object returned from the first function. But if it doesn't return anything you just get "undefined".
1
function $(id) {
  return document.getElementById(id)
}

Comments

1

You didn't return anything in the $ function, for aaa to get the element you have to return it

function $(id){
    return document.getElementById(id);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.