user1124535 user1124535 - 17 days ago 5
jQuery Question

How to reference ID of DIV sending JavaScript call?

If I have:

<div id="selectbox" onclick="selectme();">
</div>


And if I call:

function selectme()
{
var divselection=$(this);
}


I can't reference
$('#selectbox')
. What's the best way of referencing back to the div without having to passing it through as a variable?

Answer

You can't. You have 3 possibilities:

  1. Pass it as argument: onclick="selectme(this);"
  2. Fetch it by id:

    function selectme() {
        var divselection = $('#selectbox');
    }
    
  3. Not mix markup and javascript and attach the onclick handler unobtrusively:

    <div id="selectbox">
    </div>
    

    and then in a separate javascript file:

    $(function() {
        $('#selectbox').click(function() {
            var divselection = $(this);  
        });
    });