Kai23 Kai23 - 7 months ago 33
Javascript Question

JQuery vs GetElementById

I'm trying to do something since yesterday, and I'm really stuck.
Here is what « works » for now :

<h1 onclick="functionToggle(<?php echo "'".$base."'" ?>)"> <?php echo $base ?></h1>


which echo :

<h1 onclick="functionToggle('helpers')"> helpers</h1>


And I have a div like this one :

<div id="helpers" class="hidden">
<div class="fichier">audio_extensions March 02 2013 23:35:36.</div>
<div class="fichier">ebook_extensions March 02 2013 19:42:55.</div>
<div class="fichier">movie_extensions March 02 2013 20:28:01.</div>
<div class="fichier">zip_extensions March 02 2013 19:50:21</div>
</div>


The thing is : With this function, in JS :

<script>
function functionToggle(elem){
etat=document.getElementById(elem).style.display;
if(etat=="none"){
document.getElementById(elem).style.display="block";
}
else{
document.getElementById(elem).style.display="none";
}
}

</script>


This works. I just wanted to know how to do this with JQuery ? I have tried something like this :

<script>
function functionToggle(elem){
$("#elem").toggle();
}
</script>


and many other combinaison, but it doesn't work. I don't have any error, it simply doesn't work.

If you have a solution :)

Answer

You need to pass the actual id of your element.

<script>
    function functionToggle(elem) {
       $('#' + elem).toggle();
    }
</script>