Search code examples
jquerytoggleclass

Apply class name of clicked object to another jQuery


I have a function that takes the text and url of a link and inserts it elsewhere when you click it like so:

$(document).on( 'click', 'nav a', function( event ) {  
  $("#nav-tabs .ui-tabs-active a").text(this.text);
  $("#nav-tabs .ui-tabs-active a").attr("href",this.href);
  return false
}); 

That works fine. But I also want to grab the classname from it, and I can't figure out the syntax. I tried:

$("#nav-tabs .ui-tabs-active a").toggleClass(this.class);

But that doesn't work. Suggestions?


Solution

  • // Use some static "#parent" ID instead of document
    $("#parent").on( 'click', 'nav a', function( event ) {  
      event.preventDefault(); // instead of  return false;
      alert( this.textContent +' '+ this.getAttribute("href") +' '+ this.className );
    });
    

    Note that this.href might return you the full URI path instead of the exact element's href attribute value.

    Fiddle Demo

    or using the respective jQuery methods:

    $("#parent").on( 'click', 'nav a', function( event ) {  
      event.preventDefault();
      var el = $(this);
      alert( el.text() +' '+ el.attr("href") +' '+ el.attr('class') );
    });