Home > Mobile >  jQuery: delete a section if it does not have a specific class
jQuery: delete a section if it does not have a specific class

Time:10-08

There is something like this markup:

<section id="school_section" class="several classes and the class termid_[some number here]">
    <section class="several classes and the class termid_5 school_course_section"></section>
    <section class="several classes and the class termid_8 school_course_section"></section>
    <section class="several classes and the class termid_1 school_course_section"></section>
</section>

It is necessary to get the termid_ of the main section. Compare the classes of child sections with the received class from the main section and if there is no such class, then hide them.

For example, if section#school_section contains the termid_8 class, then in this example need to hide the termid_5 and termid_1 sections.

jQuery(function ($) {
    var current_termID = $('#school_section').attr('class').match(/(?:\s|^)termid_(\d )/)[1];
    if ($('.school_course_section').hasClass(current_termID) == '') {
        $(this).hide();
    }
});

I've done something like this, but so far it's not working as expected.

I will be grateful for any help)

CodePudding user response:

Use [0] to get the entire match, which includes the termid_ prefix.

The if statement just tells you if there are any elements with the matching class, it doesn't select them. Use current_termID in a selector to select the matching elements and call .hide() on that.

jQuery(function($) {
  var current_termID = $('#school_section').attr('class').match(/\btermid_\d /)[0];
  $(`.school_course_section:not(.${current_termID})`).hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="school_section" class="several classes and the class termid_8">
  <section class="several classes and the class termid_5 school_course_section">class 5</section>
  <section class="several classes and the class termid_8 school_course_section">class 8</section>
  <section class="several classes and the class termid_1 school_course_section">class 1</section>
</section>

CodePudding user response:

Find the term from the class. Use that to filter out the ones that match. Hide the others

var elem = $("#school_section");
const term = elem[0].className.match(/(termid_\d )/);
elem.children().not("."   term).hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="school_section" class="several classes and the class termid_8">
  <section class="several classes and the class termid_5 school_course_section">5</section>
  <section class="several classes and the class termid_8 school_course_section">8</section>
  <section class="several classes and the class termid_1 school_course_section">1</section>
</section>

  • Related