I am trying to add a javascript class show with dropdown-content, but it is not adding there infact while console logs are working perfectly fine upto the last scope of the javascript script tag. Can anyone help me out from this?
The text with the id is basically coming from django database which is unique.
<div class="eps_dots more_dropdown dropdown">
<a href="#" onclick="get()" id="{{course.course_id}}" class=""><i class="uil uil-ellipsis-v"></i></a>
<div class="dropdown-content ">
<span><i class="uil uil-heart"></i>Save</span>
<span><i class="uil uil-ban"></i>Not Interested</span>
<span><i class="uil uil-windsock"></i>Report</span>
</div>
</div>
<script>
function get() {
const focused = document.activeElement.getAttribute("id");
console.log(focused);
menu(focused);
}
function menu(focused) {
const path = '#' + focused + ' .dropdown-content';
console.log(path);
$(path).toggleClass("show");
}
</script>
.eps_dots .show{
display: block !important;
}
2
Answers
Given that you’re using jQuery, you should not be retrieving the
id
attribute of the clicked element as a string to manually concatenate a selector together.In addition, you should be using unobtrusive event handlers to bind your events, not inline
onclick
attributes. This would allow you to get a reference to the clicked element from the event that’s passed to the handler as an argument. From there you can traverse the DOM to find the.dropdown-content
to toggle the relevant class.In the "menu" function you have used the given path does not exist because the id would not be parent of the dropdown-content, but instead it would be it’s sibling so it would never work.
For your code to work the .dropdown-content should be wrapped inside the anchor tag like this
But as this isn’t the case you should try using the sibling format
Here the nextSibling would be your dropdown-content element