Unable to choose a child div using jQuery

<div class='class1'>
  <div class='class2'>
    <div class='class3'>
      some unique text
    </div>
    <div class='class5'>
      more unique text
    </div>
  </div>
</div>

I need to target div.class1 excluding div.class5, but the method I tried is not effective in achieving this.

$('.class1').not('.class5')

Answer №1

Using the not('.class4') method in jQuery allows you to eliminate the element that has the class class4 from the selected elements.


To filter out elements with .class1 that do not contain .class4, you can combine the :not() and :has() pseudo-class selectors.

$('.class1:not(:has(.class4))').css('color', 'red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='class1'>
  <div class='class2'>
    <div class='class3'>
      some text
    </div>
    <div class='class4'>
      some text
    </div>
  </div>
</div>
<div class='class1'>
  <div class='class2'>
    <div class='class3'>
      some text
    </div>
  </div>
</div>


UPDATE : Want to access the content of an element excluding .class4? Simply use the clone() method to clone the element, remove .class4, and retrieve the remaining content.

console.log(
  $('.class1')
  // clone the element
  .clone()
  // find `.class4` elements
  .find('.class4')
  // remove them
  .remove()
  // go back to previous selector
  .end()
  // get html content
  .html()
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='class1'>
  <div class='class2'>
    <div class='class3'>
      some text
    </div>
    <div class='class4'>
      some text
    </div>
  </div>
</div>

Answer №2

I am interested in extracting all the content from div.class1 except for [...] div.class4

To achieve this, you can utilize the attribute selector:

  • div[class] targets any div with a class attribute.
  • div[class="class4"] selects any div with a class attribute specifically set to class4.
  • div[class!="class4"] picks any div with a class attribute that is not equal to class4.

Therefore, your required selector would be:

div div[class!="class4"]

This targets any div inside another div where the class name is not class4.

Here is a Functional Example:

$(document).ready (

    function() {
        $('div div[class!="class4"]').css('borderWidth','3px');
    }
);
div {
margin: 12px;
width: 50%;
border: 1px solid rgb(0,0,0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="class1">

<div class="class2">
<div class="class3">
some text
</div>
<div class="class4">
some text
</div>
</div>

</div>


For thoroughness, here are the jQuery and JavaScript equivalents...

Using jQuery:

    function() {
        $('div div[class!="class4"]').css('borderWidth','3px');
    }

Using JavaScript:

var selectedDivs = document.querySelectorAll('div div:not(.class4)');

for (var i = 0; i < selectedDivs.length; i++) {
    selectedDivs[i].style.borderWidth = '3px';
}

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

Tips for utilizing a function to assess ngClass conditional statement in Angular 2

So as I loop through my list using *ngFor, the code snippet is like this: [ngClass]="{'first':isStartDate(event,day)}" The function isStartDate is defined in my component. An error message appeared: "Unexpected token : " ...

Discovering the required rotation angle for an object to directly face another using JS HTML5 CANVAS

Hey there, I'm currently working on a game project in Javascript where I have a player and a cursor. I already know the positions of both objects, but what I need help with is determining the angle in degrees or radians that the player needs to rotate ...

Can an image indicator be shown when I click the save button and make an ajax call?

Currently, I am utilizing .net MVC 3 for my project. I have implemented an AJAX call to save questionnaire answers and now require an image indicator, similar to a loading icon, to inform users that their responses have been successfully saved. <input ...

Position the text on the left side while also centering it within my div

I am attempting to center align some links within my div, while also ensuring that the text of the links is aligned to the left. However, I have been unsuccessful in achieving this. I can either align them to the left or center, but not both simultaneousl ...

I am looking to eliminate any special characters from a designated section of a string using Javascript

I have a string that looks like this: var myString = '{"key1":"value1", "key2":"value2", "key3":"value3"}'; My objective is to remove double quotes and other special characters only from value3. Sometimes the string may look like: var myStrin ...

Activate outline styling for Bootstrap radio buttons when clicked

I was in the midst of developing my bootstrap application. Every time I click on a radio button, there is a noticeable blue outline as shown here: https://i.sstatic.net/Uzm7b.png I attempted to address this issue using the following CSS code: .form-chec ...

The header row in my table multiplies each time an AJAX call is made

HeaderRowMultiplesEachTimeAjax My web grid table in JavaScript consists of a complete HTML table. The top header, which acts like a colgroup caption table, is built through JavaScript insertion as shown below: var headerRow = "<tr><th colspan=&a ...

What advantages do constant variables offer when selecting DOM elements?

What is the significance of declaring variables as constant when selecting elements from the DOM? Many developers and tutorials often use const form = document.querySelector('form'); ...

Ways to ensure that the height of a div remains consistent across all scenarios

https://i.sstatic.net/6LY1C.png Below is the code snippet, which utilizes bootstrap. I need to set a fixed height for a div that is populated dynamically from a database. The goal is to maintain the height of the div regardless of the content length. If ...

Is it possible to use Ajax to prompt a pop-up window for basic authentication when logging in?

While attempting to access the reed.co.uk REST web API in order to retrieve all related jobs, I am encountering an issue. Despite passing my username and password, a popup window keeps appearing when I call the URL. The alert message displayed reads: i ...

Change the color of the navbar when scrolling using bootstrap and jquery

Using Bootstrap to design a navigation bar, I have two main goals: I want the navbar to change color when the page is scrolled down by 20%, and then revert back to its original color when scrolling back to the top. When the collapse featu ...

retrieving the current value of a variable from a jQuery function

I've done my best to keep things simple. Here's the HTML code I've put together: <div id="outsideCounter"><p></p></div> <div id="clickToAdd"><p>Click me</p></div> <div id="in ...

Adding information to a database by utilizing Jquery, Ajax, and PHP

Trying to use ajax to submit data to a database has been a challenge for me. Even with a simple code test, I can't seem to make it work. Here is the HTML/ajax code snippet: <?php include("osb.php");?> <script type = "text ...

What is the order of reflection in dynamic classes - are they added to the beginning or

Just a general question here: If dynamic classes are added to an element (e.g. through a jQuery-ui add-on), and the element already has classes, does the dynamically added class get appended or prepended to the list of classes? The reason for my question ...

I'm looking to add CSS transitions, like fade-ins, to a list of items in React in a way that the animations occur one after the other upon rendering. How can this be achieved?

I've scoured the depths of Stack Overflow and combed through countless pages on the internet in search of an answer to my query, but alas, I have not found a solution. So, my apologies if this question is a duplicate. Here's my conundrum: https ...

Display iframe as the initial content upon loading

Seeking solutions for loading an iframe using jQuery or Ajax and outputting the content to the page once it has been loaded. The challenge lies in loading an external page that may be slow or fail to load altogether, leading to undesired blank spaces on th ...

assigning the browser's width to a variable within an scss file

Is there a way to dynamically set the browser's width as a variable? I am familiar with @media queries, but I need to calculate the browser's width for a specific purpose. I attempted using jQuery to achieve this, and it works well with a fixed ...

The visibility of the button background created with :before will only be apparent when a content property is specified

There's an unusual issue I've encountered... I have a simple button, nothing out of the ordinary, just a basic button like this <button class="btn btn--error"> Button Text </button> Now, I want to add an image next to my button ...

Calculate the total count of responses within the JSON data returned

Hello all, I need some guidance on calculating the total number of responses in a JSON response that adhere to a specific rule using JavaScript. Here is the JSON response that I am discussing: [ { "InvoiceNumber":"INV0319", "InvoiceOrd ...

Having trouble setting up a page layout with CSS grid or grid-template-areas

Hey everyone, I'm a beginner in the world of HTML, CSS, and JS and this is my first time reaching out for help. I've been searching through various forums and spending quite some time on this particular issue, but unfortunately, I haven't fo ...