If the section has an active class, then add its id to the body as a class?

I would be grateful if you can help with this, I cannot decide. I'm trying to create a function: "if any section has class" active "=> take this section id then add it to the body as a class element, otherwise remove it"

This code is below, but it doesn't work as expected or when I go to the next section, the new class is not added and the previous one is removed.

<body class="">
    <section id="home" class="active">
    </section>

    <section id="about" class="">
    </section>
</body>

if ($('section').hasClass('active')) {
    var dataSection = $('section').attr('id');
    $body.addClass(dataSection.replace('#', '') + '-active');   
} else {
    $body.removeClass('home-active');
}

      

+3


source to share


3 answers


When you use $('section').attr('id')

that will always return the id

first section, you need to use this

internally section

in:

$('section').attr('id');

      

Should be:

$(this).attr('id');

      

This way it will get the ID of the current section. There is also no need to replace both lines, which can be concatenated into:



$body.addClass($(this).attr('id') + '-active');

      

NOTE. You can always get the active section using only the selector, for example:

$('section.active')

      

Hope it helps.

+1


source


Try using it this

here.



if( $(something).hasClass("active") ){
    var grabId = $(this).attr("id");
    $("body").attr("id", grabId);
}

      

+1


source


Will actually $('section').attr('id')

give you the id attribute without #

, you can use it directly, you can see the body class

changed accordingly in the following demo:

if ($('section').hasClass('active')) {
  $("body").addClass($('section').attr('id') + '-active');
} else {
  $("body").removeClass('home-active');
}

console.log($("body").attr('class'));
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body class="">
  <section id="home" class="active">
  </section>

  <section id="about" class="">
  </section>
</body>
      

Run codeHide result


Note:

Note that you are using $body

which you have not yet declared, use $("body")

instead to reference the body of the document.

+1


source







All Articles