In the case that the parent contains a child class, consider using CSS or JQuery to conceal the second child class within the

Can you assist me in hiding the child element with the class of .secondchild within a parent element that has a child class?

Below is the code snippet:

HTML code

<div class="parent">
    <div class="child">
        children
    </div>
</div>
<div class="mother">
    <div class="secondchild">
        second-child
    </div>
</div>

I tried using the following script but it did not work:

if ($(".parent").hasClass("child")) {    
    $('.mother .secondchild').hide()
}

Answer №1

if the parent div does not contain a child class, your script will not produce the desired result. give this a try

if($('.parent').children().hasClass('child')){
    $('.mother .secondchild').hide();
}

VIEW DEMO

UPDATE

As per the OP's comment, hide the div on button click.

Html

<button id="btnClick">
Click Me
</button>

JS

$('body').on('click','#btnClick','',function(){
   if($('.parent').children().hasClass('child')){
      $('.mother .secondchild').hide();
   }
});

UPDATED DEMO

Answer №2

    $(function(){
        $("body").on("click",".click",function(){
            if ($(".parent ").children("div.child")) {
                $('.mother .secondchild').hide()
            }
        })
    });
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <div class="parent">
        <div class="child">
            children
        </div>
    </div>
    <div class="mother";>
        <div class="secondchild">
            second-child
        </div>
    </div>;
    <button class="click">
        button
    </button>
</body>
</html>

Answer №3

Achieve this task without the need for any if statements

$(".parent:has(.child)").next().find(".secondchild").hide()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <div class="child">
    children
  </div>
</div>
<div class="mother">
  <div class="secondchild">
    second-child
  </div>
</div>

Answer №4

Simple solution - just swap out "hasclass" with "has". Problem solved!

if($('.main').has('.sub')){
   $('.container .inner').show();
}

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

The typography text exceeds the boundaries of the Material-UI CardContent

In the React Material-UI framework, I am working with a CardContent component that looks like this: <CardContent className={classes.cardContent}> <Typography component="p" className={classes.title} variant="title"> {this.props.post.title ...

Error message: 'sass' is not recognized while trying to execute the start script

I'm struggling to streamline the process of compiling scss into css. After setting up node.js, npm, and node-sass, I attempted to create a command for compilation. Here is the run script I came up with: "start": "sass ./sass/style.scss ...

Having trouble with log4js-node in Node.js not recording logs to file?

Not a expert in nodes, this is my first time using log4js-node. I am attempting to log my ERROR logs and any console logs to a file named log_file.log using log4js on a nodejs server running Express. Below is my configuration file: { "replaceConsole": ...

Utilizing the <style scoped> feature within my Angular template

When adding CSS styles in the specified htm file's templateUrl while loading a directive, I wonder if this is a bad idea. Will it be repeated every time the template is instantiated on the rendered page, or does Angular handle this differently? By usi ...

ng-model to interact with dynamically loaded elements

My dynamic list contains various items, such as cars, and is not of fixed length. Upon loading, the list appears as follows: itemList = [ { id: 0, name: 'bmw' }, { id: 1, name: 'audi' }, { id: 3, name: 'vw' }, ...

Retrieving all selected values from a dropdown list using Jquery Chosen upon form submission

I am currently utilizing the Jquery Chosen Plugin to enhance my website. One of the features I have implemented is a MultiSelect List on my Page. <select name="articles_on_this_menu" multiple="multiple" data-placeholder="Choose Articles" id="articles_ ...

Deliver acquired post information to HTML using the read file technique

I've been diving into the world of nodeJS, jquery-mobile, and HTML5. Below is a snippet of my code: Fetching post data from an html form: req.addListener("data", function(postDataChunk){ postData += postDataChunk; console.log("Received POST ...

How can I remove the excess space above and below tables that have differing numbers of rows?

Forgive me if my question seems basic or if there are any errors in it. I am new to HTML/CSS and collaboration tools like this platform. While I understand that these are not your typical HTML tables, they are what I've found to be the most effective ...

Handling button and AJAX requests in Node.js involves creating event listeners for

I'm in the process of developing a single page application and I'm second-guessing my approach. Currently, I have a system in place where each button that requires a callback from the server triggers an ajax request. On the server-side, I handle ...

What is the best way to retrieve the local image path, transform it into a File object, and subsequently transfer it to firebase?

My current form includes a signup option where users can choose to upload a profile picture. In case they do not upload a profile picture, I aim to use a default one (think of the default Facebook profile picture). The image is imported as: import defaul ...

Angular 2 template can randomly display elements by shuffling the object of objects

I am working with a collection of objects that have the following structure: https://i.stack.imgur.com/ej63v.png To display all images in my template, I am using Object.keys Within the component: this.objectKeys = Object.keys; In the template: <ul ...

Guide to adding a theme switcher feature to your current React website

Currently, I am faced with a challenge involving two theme files, theme.js and theme-dark.js, within the context of a complex React-based website. Despite having already set up the site, I am struggling to find a way to allow users to seamlessly switch bet ...

Tips for sharing an Environment Variable with the frontend in Next.js

The Challenge Trying to pass an environment variable to the front end in order to display a map from MapBox. My Approach I placed the API Key at the root of my directory: //.env.local MAPBOX_KEY="abc123" On the front-end, I attempted to acce ...

Is it possible to anticipate a particular word following a route parameter in Node.js?

My current route setup looks like this: router.get('/:board/:threadId', function(req, res, next) { // performing actions here }); When users visit /a/1, it triggers the route with board = a and threadId = 1. Now, I want users to have to vis ...

Establishing a primary data format for a backbone collection

Is there a way to configure a Backbone collection to always include a content type of "application/json" in every request it makes? I have tried the following code snippets: myCollection = Backbone.Collection.extend({ headers: {"Content-Type": 'ap ...

Can jQuery and Google Analytics be loaded together in a single process?

My current setup includes the following: <script src="http://www.google.com/jsapi?key=..." type="text/javascript"></script> <script> //<![CDATA[ google.load('jquery', '1.6'); //]]> </script> &l ...

In React + TypeScript, learn how to effectively pass down a function from a container component to a

I am currently working on developing a tabs application using React and Typescript. The main component, Tabs, manages the state and passes it down to the Content component. Additionally, I have implemented a function called 'handleName' which is ...

Using JavaScript to fetch elements by their ID along with a button

UPDATE: I have corrected the semi-colons, case sensitivity, and brackets in the code. It functions properly if I eliminate the functions after buttonPARTICULAR! Why is that? UPDATE: Issue resolved. My mistake. Apologies!!! :-Z When I simplify it like thi ...

What is the most efficient way to transmit JSON data from a browser to a REST endpoint via Node.js, specifically in gzip format?

Currently working with node.js and express, I have a home page that hits my REST endpoint (PUT) after loading to send some JSON data. The data is not gziped when sending to the endpoint, but I want it to be in gzip form once it reaches the endpoint. Is thi ...

Implementing OR logic for event handlers with jQuery

I have a dropdown list where I want to make an ajax call on both onchange and onload events. $('#id').change(function() { // ajax call }); Instead of just calling the ajax on change, I also need it to be triggered on page load. My current log ...