Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
If section has class active then add it's id to body as a class?

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

This the code below, but it's not working properly or when I scroll to next section new class is not being added and previous one 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');
}
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Try using this here.

if( $(something).hasClass("active") ){
    var grabId = $(this).attr("id");
    $("body").attr("id", grabId);
}
over 4 years ago · Santiago Trujillo Report

0

When you use $('section').attr('id') that will always return the id of the first section, You need to use this inside of section in :

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

Should be :

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

So it will get the id of the current section, Also no need for the replace the both lines could be combined to :

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

NOTE : You could always get the active section using just selector like :

$('section.active')

Hope this helps.

over 4 years ago · Santiago Trujillo Report

0

Actually $('section').attr('id') will give you the id attribute without # you can use it directly, you can see body class changed accordingly in the folowing 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>

Note:

Note that you are using $body which you haven't declared, use $("body") instead to refer document body.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!