Master-Antonio
Master-Antonio

Reputation: 149

Jquery/Javascript ( Convert from ID to Class )

I did this script. But now i need to convert these id to classes because should I put it in other elements of the page.

card ---> .card

flip ---> .flip

 var init = function() {
      var card = document.getElementById('card');
      
      document.getElementById('flip').addEventListener( 'click', function(){
        card.toggleClassName('flipped');
      }, false);
    };
    
    window.addEventListener('DOMContentLoaded', init, false);

Can you help me?

SOLUTION :

$(function() {
  var card = $('.card');
  
  $('.flip').on( "click", function(){
    card.toggleClass('flipped');
    return false;
  });
});

Upvotes: 2

Views: 1688

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Since you have tagged with , I would give this:

// Once document is loaded,
$(function () {
  // Change all the `#card`, `#flip` to classes:
  $("#card, #flip").addClass(function () { return this.id; }).removeAttr("id");
});

First it selects all the #card and #flip, there should be only 2 elements. It adds their respective id as class and removes the id attribute.

Snippet

// Once document is loaded,
$(function () {
  // Change all the `#card`, `#flip` to classes:
  $("#card, #flip").addClass(function () { return this.id; }).removeAttr("id");
});
.card {background: #f99;}
.flip {background: #9f9;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="card">Card</div>
<div id="flip">Flip</div>

If you just wanna add the extra classes, then you can use this:

$(function() {
  var card = $('.card');

  $('.flip').on( "click", function(){
    card.toggleClass('flipped');
    return false;
  });
});

Upvotes: 2

Related Questions