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

Foundation: the importance of source order (without using flex grid)

I have a 3-column grid, with content and a sidebar. On small and medium devices each takes up 12 columns. Take a look at the example here: cdpn.io/anon/pen/bqENqG. I am looking to have the sidebar appear after the articles on small and medium devices like ...

Using jQuery to remove the 'active class' when the mouse is not hovering

I recently came across this amazing jQuery plugin for creating slide-out and drawer effects: However, I encountered a problem. I want to automatically close the active 'drawer' when the mouse is not hovering over any element. The jQuery plugin c ...

HTML5 Slideshow with Smooth Image Transitions

So, I have created an HTML5 image slideshow and it's working perfectly on my localhost. However, I am puzzled as to why there is no transition effect within the slideshow. I was expecting something like fading out the first picture and then having the ...

Get rid of the margins on your Wordpress theme

Currently, my Wordpress site is using the Tesseract theme which can be found at (http:// instantiwebs . com) I am interested in removing the left/right margins on all elements, similar to what has been done on this website: . Interestingly enough, they al ...

Background positioning in IE8 does not display as intended

I'm experiencing an issue with the image background not displaying in IE8. You can view the page here, and the arrows on the accordion are not visible. Here is the CSS: .closed h2.accordion_h3 { background: url(mysource_files/down.png) no-rep ...

Determine the currently active view on a mobile device

I am trying to determine whether the user is viewing the website vertically or horizontally on their mobile device or iPad in order to adjust the image scale accordingly. For example: If the user is viewing the page horizontally, I want the image style t ...

How can you assign a strokeStyle color to a Canvas using a CSS property?

Our team is currently working on an Angular2 / Ionic 2 project where we have implemented a HTML Canvas element that allows users to draw on it. One challenge we are facing is how to set the Canvas strokeStyle property using a color provided by a CSS style. ...

Using jQuery to enhance an HTML form

Currently, I am in the process of creating an HTML form for user sign up which includes typical fields such as username, password, and email. My intention is to transfer the entire HTML form to another .php file using the POST method. The second .php file ...

It appears that the jQuery script is not loading properly

For my wordpress site, I have integrated jQuery using the wp_enqueue_script function along with the jQZoom script. In the header of my site, you can find the following lines in this order: <link rel='stylesheet' id='jQZoom_style-css&apo ...

issue with transparent html5

Here is the code snippet I am struggling with: function clear(){ context2D.clearRect(0, 0, canvas.width, canvas.height); } function drawCharacterRight(){ clear(); context2D.setTransform(1, 0.30, 1, -0.30, 10, 380);//having issues here c ...

eliminate the offspring of a component (chessboard)

Hey there! I'm currently working on developing a chess game and I could really use your expertise to help me solve an issue. In my code, when I try to move a piece in the game, this is what happens: 1. First, I remove the existing piece from its cu ...

Is there a way to enhance the height of Bootstrap combobox items? Can this be achieved?

Is it possible to improve the height of Bootstrap combobox item? How can I achieve that? 1 2 3 4 ...

Position a div in the center both horizontally and vertically within a section, ensuring that each section expands to fill the entire page when scrolling

I'm currently working on coding a page layout where each section takes up the entire screen. My goal is to have the content within each section centered both vertically and horizontally. I'm unsure if this is achievable, so any guidance or advice ...

Jquery Toggle not applying class change on mobile devices

Check out my website: . There's a menu option called Services with a dropdown feature. Here is the code for it: <li class="dropdown menu-services"><a class="dropdown-toggle" href="#" data-toggle="dropdown" data-target="#">Services <b c ...

Each Browser Approaches Simple Search Fields in its Own Unique Way

In the process of creating a search field with an input field and an svg icon, I encountered different browser behaviors in Chrome, Firefox, and IE11. Chrome – the preferred version Firefox IE11 (confusing) Check out the working demo of the code on c ...

Troubleshooting Problem with CSS Display in Spring Security 3.2

After deciding to integrate 'Spring security 3.2.0' into my current web application, which was originally developed without Spring and utilizes Primefaces & EJB 3, I encountered a challenge. Upon starting the basic configurations, I noticed that ...

Tips on achieving horizontal scrolling for div overflow instead of wrapping onto a new line

It's a frequent occurrence in mobile apps to have a navbar with selectable text options that overflow horizontally without breaking into a new line. Instead, users must scroll horizontally to access all the options available. Is there a way for me to ...

The functionality of aos.css seems to be malfunctioning on a Django-powered website

I recently set up a django backend website and attempted to incorporate CSS in my HTML using the following code snippet. {% load static %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-wid ...

forming a boundary that stands alone, unattached to any other boundaries

I am trying to design a navigation bar that resembles the one depicted in the image provided. The concept involves creating a navigation bar where each border is separated from the others, potentially achieved using hr tags. However, I am struggling to fi ...

Aligning Bootstrap Buttons

How do I create a gap between my Bootstrap4 button and the top of the table, while also aligning it to the edge of the table? <div class="container"> <div class="table-title"> <div class="row"> ...