Zabson1994 Zabson1994 - 1 month ago 8
Javascript Question

pass element Html to function from onclick

I want to create element from code and add as parameter in onclick, element. I tried this: my fiddle

<div class="aaa">
<div class="bbb">
bbb
</div>
</div>

$(document).ready(function(){
elementToPass = $('.aaa').children()[0];
var element = '<div class="ccc" onclick="myFun(' + elementToPass + ')">ccc</div>';
$('.aaa').append(element);
});

myFun = function(){
console.log('its working');
}


but it caused error;/

Answer

notice the difference between an element itself and the variable being converted to string while concatenated to other string

i.e. don't perform: 'some text' + elementToPass + 'remaining text' because elementToPass will become a string rather than the object you intend

$(document).ready(function(){
    var elementToPass = $('.aaa').children()[0];
    var element = '<div class="ccc" onclick="myFun()">ccc</div>';
    $('.aaa').append(element);

    myFun = function(){
        console.log('its working: ' + elementToPass);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<div class="aaa">
    <div class="bbb">
        bbb
    </div>
</div>