Q:

JavaScript - how to pass variable through a function from loop

here's what i try to accomplish

when user click div class='container' it will alert the innerHTML of his spesific child
(p class='primary_key' )
no JQuery

index.html
<html>
<head>
    <style>
        .primary_key{
            display: none;
        }
    </style>
    <script type="text/javascript" src="script.js"></script>
</head>
<body>

    <div>
        <div class="container">
            <p class="primary_key">1</p>
            <p class="content">content1</p>
        </div>
        <div class="container">
            <p class="primary_key">2</p>
            <p class="content">content2</p>
        </div>
    </div>
</body>
</html>

script.js
    window.onload = function(){

    var allContainer = document.getElementsByClassName('container');
    for(var i=0; i<allContainer.length; i++){
        var container =  allContainer[i];
        allContainer[i].onclick = function(e){
            clickContainer(container);
        }
    }
}

function clickContainer(ele){
    var selectedId = ele.getElementsByClassName('primary_key')[0].innerHTML;
    alert(selectedId);
}

it supposed to

when user click first container it will show/alert 1
when user click second container it will show/alert 2

but my code always alert = 2
jsfiddle

A:

The reason this is happening is because the for loop is changing the container so when the element is clicked it should alert 2 either way because container is the last container, you can use a closure like this 
for(var i = 0; i < allContainer.length; i++){
    (function(container){
        container.onclick = function(e){
            clickContainer(container);
        }
    })(allContainer[i]);
}

This "captures" the container in a function 
Or event better you can remove everything out of your for loop, like so
for(var i = 0; i < allContainer.length; i++){
     clickContainer(allContainer[i])
}

function clickContainer(element){
    element.onclick = function() {
        var selectedId = this.getElementsByClassName('primary_key')[0].innerHTML;
        alert(selectedId);
    }
}

I would also recommend addEventListener('click', handler) over onclick

A:

Try this:
allContainer[i].onclick = function(e){
    clickContainer(this);
}

