cancel
Showing results for 
Search instead for 
Did you mean: 

Magento 2.3 add class to menu anchor tag

Magento 2.3 add class to menu anchor tag

I am trying to add class to the top menu item in Magento. I was able to add class to the <li> tag by overriding the Topmenu.php file. Now I want to add a class to the <a> tag too. Below is the Topmenu.php content. I have added the class nav-item to the <li> tag and it works. Similarly, I want to add a class to the <a> tag under the <li>

<?php

namespace Ecommerce\Menu\Block\Html;

class Topmenu extends \Magento\Theme\Block\Html\Topmenu
{
    protected function _getMenuItemClasses(\Magento\Framework\Data\Tree\Node $item)
    {
        $classes = [];

        $classes[] = 'level' . $item->getLevel();
        $classes[] = $item->getPositionClass();

        if ($item->getIsFirst()) {
            $classes[] = 'first';
        }

        if ($item->getIsActive()) {
            $classes[] = 'active';
        } elseif ($item->getHasActive()) {
            $classes[] = 'has-active';
        }

        if ($item->getIsLast()) {
            $classes[] = 'last';
        }

        if ($item->getClass()) {
            $classes[] = $item->getClass();
        }

        if ($item->hasChildren()) {
            $classes[] = 'parent';
        }

        $classes[] = 'nav-item';

        return $classes;
    }
}
1 REPLY 1

Re: Magento 2.3 add class to menu anchor tag

Hello @akhilesh4u66f7 

 

If you need to add the class in the <a> tag under the <li> then you can override _getHtml(). and you can change the below code:

$html .= '<a class="CLASS_NAME level-top" href="' . $child->getUrl() . '" ' . $outermostClassCode . '><span>' . $this->escapeHtml(
    $child->getName()
) . '</span></a>' . $this->_addSubMenu(
    $child,
    $childLevel,
    $childrenWrapClass,
    $limit
) . '</li>';

Note: Please replace "CLASS_NAME" with your actual class name and please don't remove the "level-top" class name.

 

If you find our reply helpful, please give us kudos.

 

A Leading Magento Development Agency That Delivers Powerful Results, Innovation, and Secure Digital Transformation.

 

WebDesk Solution Support Team

Get a Free Quote | | Adobe Commerce Partner | Hire Us | Call Us 877.536.3789

Thank You,


WebDesk Solution Support Team
Get a Free Quote | Email | Adobe Commerce Partner | Hire Us | Call Us 877.536.3789


Location: 150 King St. W. Toronto, ON M5H 1J9