Currently, I am working on a dropdown menu and facing an issue with setting the submenus to match the width of the top-level page.
In my HTML structure (specifically for a WordPress theme), it looks something like this:
<ul class="menu">
<li class="menu-item-has-children menu-item">
<a>Top Level Page 1</a>
<ul class="submenu">
<li class="menu-item-has-children menu-item">Sub Page 1</li>
<li>Sub Page 2</li>
<li>Sub Page 3</li>
</ul>
</li>
<li class="menu-item-has-children menu-item">
<a>Top Level Page 2 which has a different width</a>
<ul class="submenu">
<li>Sub Page 4</li>
<li>Sub Page 5</li>
<li>Sub Page 6</li>
</ul>
</li>
</ul>
I attempted to solve this using CSS initially:
ul.menu li ul {
width: 100%;
}
However, this ended up making the submenu the same width as the entire ul.menu rather than just the parent page. After trying various methods with no success, I decided to turn to jQuery for help, inspired by a post I found online.
I started with the following jquery code:
$('ul.menu li ul').width($(ul.menu li).width());
Unfortunately, this set all submenus to the width of the first 'li' element, ignoring their individual relationships with parent pages. I then tried several other approaches to target specific elements but none of them seemed to work as intended:
$('ul.menu li ul').width($(this).parent('li').width());
$('ul.menu li ul').width($(this).parent().width());
$('ul.menu li ul').width($(this).parent('li').children('a').width());
$('ul.menu li ul').width($(this).siblings('a').width());
I am wondering if the use of '$this' is incorrect in this context. If so, could you suggest a better approach to achieve what I am attempting?