I want to Show-Hide an element by clicking on an element that was created from JS code. But for some reason getElementById and getElementsByClassName not work to select these HTML elements. (Please check the Demo: http://jsfiddle.net/vy09nnco/)
Here is the HTML code:
<div id="toShow">Hello World!</div>
<div id="container"></div>
Creating the <p> element (which will be used to Show-Hide) and appending to the container div:
var code = '<p class="click-me">Click Me!</p>';
$('#container').append(code);
Here is the complete JQuery code:
$(document).ready(function () {
var code = '<p class="click-me">Click Me!</p>';
var divToShow = document.getElementById('toShow');
var clickMeDiv = document.getElementsByClassName('click-me'); // Here is the problem
var isOpenedClass = 'isOpened';
var formIsClosed = true;
$(clickMeDiv).click(function() {
$(divToShow).toggleClass(isOpenedClass);
formIsClosed = false;
});
$(clickMeDiv).click(function() {
if (formIsClosed) {
$(divToShow).removeClass(isOpenedClass);
}
formIsClosed = true;
})
$('#container').append(code);
});
When I use another element to Show-Hide, it works good (example: http://jsfiddle.net/vy09nnco/1/), that is why the problem it's only by selecting the created code.
Thanks for any help.