Jitender
Jitender

Reputation: 7969

Return in javascript

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>

Upvotes: 0

Views: 151

Answers (3)

Strelok
Strelok

Reputation: 51461

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 $.

Upvotes: 1

Musa
Musa

Reputation: 97707

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);
}

Upvotes: 1

Danil Speransky
Danil Speransky

Reputation: 30463

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

Upvotes: 1

Related Questions