My HTML code:
<div class="side-bar">
<div class="menu">
<div class="item"><a id="item1" href="#">Dynamically create submenu here</a></div>
<div class="item">
<a id="item2" href="#">Already created submenu here</a>
<div class="sub-menu">
<a href="#" class="sub-item">Sub item 1</a>
<a href="#" class="sub-item">Sub item 2</a>
</div>
</div>
</div>
</div>
My CSS:
.side-bar .menu .item .sub-menu{
background: rgba(255, 255, 255, 0.1);
display: none;
}
.side-bar .menu .item .sub-menu a{
padding-left: 80px;
}
My Jquery:
$(document).ready(function(){
$('#item2').click(function(){
$(this).next('.sub-menu').slideToggle();
});
});
This code works perfectly fine, when I click the #item2
anchor tag, the sub menu opens and closes perfectly. I want to use this same style to a sub menu that I created dynamically and attached to #item1
. This is my code:
function get_all_the_values(){
return $.ajax({
url: '/php_script.php',
type: 'POST',
data: {"input": "get values"}
});
}
$(document).ready(function(){
$('#item1').click(function(){
if(!$(this).next('.sub-menu').is(':visible')){
(async()=>{
let response = await get_all_the_values();
const arr = JSON.parse(response);
let elem = document.createElement("div");
elem.className="sub-menu";
elem.id="id1";
for(var i=0; i<arr.length; i++){
var anchor = document.createElement("a");
anchor.className="sub-item";
anchor.href="#";
anchor.innerText = arr[i];
elem.appendChild(anchor);
}
document.getElementsByClassName("item")[0].appendChild(elem);
$(this).next('.sub-menu').slideDown();
});
}
else{
document.getElementById("id1").remove();
$(this).next('.sub-menu').slideUp();
}
});
});
I have checked my response
and it's fetching the correct values from my server. I have given the same class name (sub-menu
and sub-item
to the submenu and subitems respectively) so that it follows the same style that is written in my css
.
But it doesn't work as expected. When I click the #item1
anchor, the sub menu doesn't show, even when the console
shows that it's created.
Why is that? The classname
is the same, so it should follow the same styles. Where am I going wrong?