When the banner is hidden, I would like to apply a class to the body element

function checkBanner() {
  var banner = document.querySelector('.banner-section');
  if (!banner.length) {
    document.querySelector('body').classList.add('no-banner')
  }
}

checkBanner();
<body>
  <div class="banner-section">
    <div class="banner">
      <h1>Lorem ipsum dolor sit amet.</h1>
      <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corporis, harum?</p>
    </div>
  </div>
</body>

The JavaScript code I wrote isn't functioning correctly. It's currently only adding a no-banner class to the body tag, but my intention is for a class to be added to the body tag if the banner-section class is empty.

Answer №1

When you want to validate the presence of a banner by running the code if (!banner.length), it will return true. This is because the method

document.querySelector('.banner-section')
only returns a single element, not an array, so it does not have a length property.

If you need to check if the .banner-section element contains any content, you can verify whether its innerHTML property is an empty string or not.

function checkBanner() {
  var banner = document.querySelector('.banner-section');
  if (!banner.innerHTML.trim()) {
    document.querySelector('body').classList.add('no-banner');
  }
}

checkBanner();

Answer №2

To verify if the banner contains any children, it is necessary to replace banner.length with banner.children.length

function checkBannerChildren() {
  var banner = document.querySelector('.banner-section');
  if (!banner.children.length) {
    document.querySelector('body').classList.add('no-banner')
  }
}

checkBannerChildren();
<div class="banner-section">
  <div class="banner">
    <h1>Lorem ipsum dolor sit amet.</h1>
    <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corporis, harum?</p>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with functionality of Tumblr share button

I've been attempting to integrate a Tumblr share button on my online store, but I'm having trouble getting the Tumblr Share Button (see here) to function properly. My goal is to allow users to share a customized picture of a product and include ...

Tips for customizing the appearance of a jQuery sortable target list prior to dropping items

When using jquery sortable, I am able to customize a placeholder inside a connected list specified in the connectWith option to visualize where the content will be dropped. However, I am struggling to find a way to style the actual list that contains the p ...

Error: Unable to locate module - Invalid generator instance detected. The Asset Modules Plugin has been started with a generator object that does not adhere to the API standards

Encountering an issue in nextjs when utilizing the 'asset/inline' Asset Module Type within a custom webpack configuration while running yarn dev. I attempted to utilize the 'asset/inline' asset module type to output the URI of the impor ...

Is the required attribute malfunctioning in HTML5?

I've come across some similar inquiries, but none of them address my specific question. I am working on a form where certain details are required, while others are optional. I have used the required tag for the mandatory fields. The submit button is l ...

What is the process for incorporating an external script into a Vue component?

Seeking assistance urgently... I am encountering an issue with a Vue component and an endpoint that provides a script containing a small menu with actions. However, once the script is loaded, the actions do not seem to function on the page and I cannot det ...

What is the best way to trigger my web scraper within an express route?

Within my Nodejs server's root directory, I have implemented a web scraper using needle to handle the HTTP requests for retrieving HTML data. This scraper returns an Array of data upon completion. In addition, there is an index.js file containing expr ...

Modifying the default value setting in MUI Datepicker

Currently, I am utilizing version @mui/x-date-pickers ^6.17.0. Here is the custom date picker I am using: https://i.stack.imgur.com/k8nF1.png Upon clicking the input field, the placeholder switches and a value gets appended. However, modifying the input ...

Ways to halt the execution of a setTimeout function within a loop

This question is a follow-up from this thread - setTimeout inside a loop, stops script from working I'm facing an issue with my script that fetches data from an API and stores it in a MongoDB collection. The problem seems to be related to the setTime ...

Update JavaScript variable value when there is a change in the onchange

Greetings, thank you for taking the time to read this. I am currently working with an input that includes a datepicker calendar. This calendar has variables called minDays and MaxDays which allow users to select a specific number of days. In my HTML form, ...

Identifying the unique parent component of a component within Angular

One of my components, named Com1, is imported into multiple other components. Within Com1, there is a button that triggers a function when clicked. In this function, I am trying to print out the parent component of the specific instance of Com1. How can I ...

Ensuring the vue carousel component stops rendering once all of its data has been displayed

Is it possible to stop rendering a vue carousel component once its data is displayed or after a certain amount of time? I've searched for information on this, but haven't found anything relevant. Despite it being an unusual request, I still want ...

Encountering a 404 Not Found error while attempting to reach a Node/Express endpoint from the client side

I've developed a Node.js/Express REST API to be utilized by a frontend React application for an inventory management system intended for a garage sale. When attempting to add a new product, I'm trying to access the POST route http://localhost:300 ...

JS: Decreasing the counter while calling the hide() function

If I have a standard count <?php echo "Today (".mysql_num_rows($query)."); ?> It will display as Today (10) if there are 10 entries. Beneath this counter is a while() loop that displays all the rows in a <tr>. Within each <td> in the ...

Incorporating dynamic elements without sacrificing the original static page

I have a compilation of video titles. Each title links to a page featuring the specific video along with additional details such as player information, description, and discussion. <div id="video-list"> <a href="/Video/title-1">Title 1</a&g ...

Locating the position of multiple repeated words

My question involves a complex laTeX string: let result = "\\frac{x}{2}+\\frac{3}{x}"; The task at hand is to locate the instances of "frac" in the string, store their positions in an array, find the first '}&a ...

What could be causing my SectionList to occasionally display only a single section?

I'm facing a problem with the SectionList component where it occasionally fails to display all sections, only rendering the first one. After some debugging, I may have found a solution, but I'm unsure why it resolves the issue. While my page con ...

How to Upload Your Avatar Image with the Stream-Chat API from GetStream.io

I am currently in the process of developing a Stream-Chat API project and I want to allow users to upload images directly from their devices. Upon testing, everything seems to be working fine, but the uploaded image is not displayed - only the default avat ...

Iterating through HTML table data using a JQuery for each loop

Currently, I have an HTML table that is structured in the following way: <div class="timecard"> <h3>tommytest</h3> <table class="misc_items timecard_list" border="0" cellpadding="2" cellspacing="0" style="margin:0 auto;"> < ...

Tips for updating multiple bundled javascript files with webpack

I am working on a straightforward app that requires users to provide specific pieces of information in the following format. Kindly input your domain. User: www.google.com Please provide your vast URL. User: www.vast.xx.com Select a position: a) Bottom ...

Activate the function within the same class only for the selected item

Hello there, I'm struggling to grasp how to make this particular functionality work. Basically, I have 8 divs, each containing an image used as a button with the same class (tm-img), and hidden divs with additional information. My goal is to initiall ...