Home > Mobile >  JQuery - Change className with logic conditions
JQuery - Change className with logic conditions

Time:12-27

I am looking for modifying the class name of a div according to the name of another div. I cannot make it work with JQuery.

Here is the html structure :

<div >
    <a  href="https://www.example.net/page-events/" target="_blank"></a>

    <div >
        <ul >
            <li>
                <a href="https://www.example.net/category/events/" >Events</a>
            </li>                                       
        </ul>
</div>
    
<div >
    <a  href="https://www.example.net/page-conferences/" target="_blank"></a>

    <div >
        <ul >
            <li>
                <a href="https://www.example.net/category/conferences/" >Conferences</a>
            </li>                                       
        </ul>
</div>

My goal is to modify the :



According to the text value in :


My attempt is not successful :

$(document).ready(function(){
var category = $(".category-item").html();
var newEvents = $(".div-overlay").attr('newclass','events');
var newConferences = $(".div-overlay").attr('newclass','conferences');

if (category = "Events"){
   newEvents;
} else if (category = "Conferences") {
    newConferences;
};
});

How can I make my script work ?

Details : working on Wordpress with elementor.

CodePudding user response:

You should use addClass methd

$(document).ready(function(){
   var category = $(".category-item").html();
  
   if (category = "Events"){
      $(".div-overlay").addClass('events');
   } else if (category = "Conferences") {
      $(".div-overlay").addClass('conferences');
   };
});

CodePudding user response:

You can try this code :

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  var category = $(".category-item").html();
  var newEvents = $(".div-overlay").attr('newclass','events');
  var newConferences = $(".div-overlay").attr('newclass','conferences');

  if (category = "Events"){
     newEvents;
  } else if (category = "Conferences") {
      newConferences;
  };
  
    $(".category-item").each(function() {
        var cat_val = $(this).html();
        $(this).parents('.div-overlay').attr('newClass', cat_val);
    });
});
</script>
</head>
<body>

<div >
    <a  href="https://www.example.net/page-events/" target="_blank"></a>
    <div >
        <ul >
            <li>
                <a href="https://www.example.net/category/events/" >Events</a>
            </li>                                       
        </ul>
    </div>
</div>
    
<div >
    <a  href="https://www.example.net/page-conferences/" target="_blank"></a>
    <div >
        <ul >
            <li>
                <a href="https://www.example.net/category/conferences/" >Conferences</a>
            </li>                                       
        </ul>
    </div> 
</div>

</body>
</html>

  • Related