charlene gipulan
charlene gipulan

Reputation: 21

cannot read property add of undefined vanilla JS

i am trying to convert

var target = $(this).attr('href')
$(target).addClass('active');

to javascript with

let target = this.getAttribute('href') where target is '#tab3' target.classList.add('active'); results to cannot read property add of undefined

function tabControl() {
    const tabs = document.querySelector('.tabs');
    if (!isHidden(tabs)) {
        const tabItems = tabs.querySelectorAll('a');
        for (const tabItem of tabItems) {
            tabItem.addEventListener('click', function(event) {
                event.preventDefault();
                let target = event.target.getAttribute('href'),
                    tabs = closest(this, '.tabs');
                    buttons = tabs.querySelectorAll('a'),
                    item = closest(tabs, '.tabbed-content').querySelector('.item');
                buttons[0].classList.remove('active');
                item.classList.remove('active');
                this.classList.add('active');
                target.classList.add('active');
            });
        }

Any help/explanation will be much appreciated!

html

 <article class="tabbed-content">
   <nav class="tabs">
      <ul>
          <li><a href="#tab1" class="active tab">TAB 1</a></li>
         <li><a href="#tab2" class="tab">TAB 2</a></li>
        <li><a href="#tab3" class="tab">TAB 3</a></li>
      </ul>
  </nav>
 <section id="tab1" class="item active" data-title="Tab 1">
    <div class="item-content">
      <p>Hello from tab1</p>
    </div>
</section>
 <section id="tab2" class="item" data-title="Tab 2">
   <div class="item-content">
     <p>Hello from tab 2</p>
   </div>
</section>
<section id="tab3" class="item" data-title="Tab 3">
   <div class="item-content">
     <div class="materials-container">
       <p>Hello from tab 3</p>
      </div>
   </section>
</article>

Upvotes: 0

Views: 215

Answers (2)

Reporter
Reporter

Reputation: 3948

The classic way in javascript is as follows:

this.className =  this.className + " active";

Upvotes: 0

tmhao2005
tmhao2005

Reputation: 17474

Your code would look like:

const yourElem = document.querySelector('yourSelector');
yourElem.classList.add('yourClassName')

Upvotes: 1

Related Questions