Identify all div elements with a specific class within the parent div

How can I use query selector to exclusively target the p and p2 divs inside of a r class, without selecting them if they are outside of that class?

<div>
<div class="r"><div class="p"></div><div class="p2"></div></div> //This is what I want to select, using the parent div tag name
</div>

<div class="r"><div class="p"></div><div class="p2"></div></div> //I don't want to select this if the parent div is body

CSS

.p,.p2{
height:50px;
width:50px;
background-color:orange
}

I have tried the following JavaScript code. Is it correct for achieving this?

c = document.querySelectorAll(' x >.r' ) //where x is the parent tag tagName of r 

Answer №1

Based on your specific needs, you are looking to target the descendants of the first child element only.

To achieve this, simply utilize the :first-child selector.

var firstChild = document.querySelector(".r:first-child");
var descendants = firstChild.querySelectorAll(".p, .p2");

Array.from(descendants).forEach(function(item){
  item.style.backgroundColor = "red";
});

Check out the DEMO for reference

Answer №2

If you want to select elements with a specific class, you can use the following code:

const selectedElements = document.querySelectorAll(".r .p, .r .p2");

By using a comma in the querySelectorAll method, you can separate multiple selectors. Additionally, in CSS syntax, a b signifies selecting element b inside of element a.

Answer №3

If you're looking to target elements by their class, you can use the following code:

document.querySelectorAll('div div.r .p, div div.r .p2');

These selectors can be used anywhere, such as in a style rule, without the need for extra scripting.

For example:

window.onload = function() {
  var x = document.querySelectorAll('div div.r .p, div div.r .p2');
  console.log('Found: ' + x.length);
};
<!-- Elements nested within a div -->
<div>
  <div class="r">
    <div class="p">p inside div and div.r</div>
    <div class="p2">p2 inside div and div.r</div>
  </div>
</div>

<!-- Elements nested within body -->
<div class="r">
  <div class="p">p inside body and div.r</div>
  <div class="p2">p2 inside body and div.r</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

Utilizing Next.js and Redux for Enhanced Authentication Experience

I have encountered an issue while trying to authenticate the user upon loading and needing to run the authentication process in the pages/_app.js file. The error I am facing is useReduxContext.js:24 Uncaught Error: could not find react-redux context value; ...

What is the best way to instantiate objects, arrays, and object-arrays in an Angular service class?

How can I nest an object within another object and then include it in an array of objects inside an Angular service class? I need to enable two-way binding in my form, so I must pass a variable from the service class to the HTML template. trainer.service. ...

What is the recommended approach for passing parameters to a JavaScript function from an anchor tag?

I recently came across this intriguing question: What is the best practice for using Javascript and Anchor Tags? The suggestion provided in response to this query involves utilizing the following code snippet: <a id="foo" href="#">Click Me</a&g ...

Executing multiple Ajax requests on CodeIgniter 3 from two separate pages

I am facing a critical need for a code review and unfortunately, I am unsure of where else to seek assistance besides here. Let me outline my current task: I am working on a user profile page that is designed to showcase users' comments. Users have t ...

Using Angular promises and the $http service

ng.module('app') .service('CardService', ['$http', CardService]) function CardService($http) { this.$http = $http; var self = this; $http.get('http://localhost:3000/db').success(function(data) { ...

After utilizing the function, the forward and back arrows are no longer visible

After setting up my slideshow, I encountered an issue where clicking the next or previous buttons caused them to shrink down and turn into small grey boxes. Has anyone experienced this before? This relates to PHP/HTML if ($_SERVER['REQUEST_METHOD&ap ...

Issue occurred while trying to set the value from an API call response in the componentDidMount lifecycle method

There is a boolean variable disableButton: boolean; that needs to be set based on the response received from this API call: async getDocStatus(policy: string): Promise<boolean> { return await ApiService.getData(this.apiUrl + policy + this.myEndpo ...

Activate a click on a div element to enable smooth scrolling when using the page down and page up keys

Whenever I directly click on my div, the pageUp and pageDown keys scroll the contents of the div. But when I trigger a click programmatically, the scrolling with pageUp and pageDown stops working. How can I enable scrolling with pageUp and pageDown without ...

What could be causing the issue with lodash throttle not functioning correctly in the useWindowSize custom hook?

I'm attempting to implement a resize event with throttle, but I'm encountering an issue. To troubleshoot, I have tried the following: import {throttle} from 'lodash' export function useWindowSize() { const [windowSize, setWindowSize] ...

inSession variable in express: set to false

i keep receiving inSession:false when attempting to log in, it is expected to return true. I am utilizing express session, in combination with postges and sequalize. I have logged the state values and they are being rendered correctly, so they are n ...

Ways to showcase INPUT TYPE when making a Selection?

I've been struggling with a simple issue and despite trying multiple solutions, I can't seem to get it right. I have a form where I'm using the <select> tag with two options: coo and uh. What I want is for an additional input type fiel ...

Facebook has broadened the scope of permissions for canvas applications

I am in the process of developing a Facebook canvas application that requires extended permissions for managing images (creating galleries and uploading images) as well as posting to a user's news feed. I am currently facing challenges with obtaining ...

The jQuery ajax function functions flawlessly on a local environment, but encounters issues when used on a

After spending the entire day researching this issue, it appears to be a common problem without a solution in sight. The challenge I am facing involves using jquery's $.ajax() function to update database values through a service call. While it works ...

Make sure all of the inner tags are properly contained within their respective containers

In my explanatory bubble, I aim to include text within the explain-header div as a container for my explanations: /*Explain Bubble*/ .explain-container { position: relative; overflow: hidden; max-width: 70vw; max-height: 50vh; background-c ...

Toggle the display of dropdown 2 or dropdown 3 depending on the option chosen in dropdown 1

I am struggling with a form that contains 3 dropdowns: <select id="1" required> <option value="">Choose an option</option> <option value="1">Apple</option> <option value="2">Orange ...

Generating modal pages on the fly

One thing that's been on my mind is creating modals for my page. Typically, I would include the HTML code for my modal directly in the page like this: <div class="my-modal"> <form action="/home/index"> <input type="text" class="txt- ...

Transferring pictures between folders

I am currently developing an Angular app that involves working with two images: X.png and Y.png. My goal is to copy these images from the assets folder to a specific location on the C drive (c:\users\images) whose path is received as a variable. ...

Why is the function app.get('/') not triggering? The problem seems to be related to cookies and user authentication

Need help with app.get('/') not being called I am working on implementing cookies to allow multiple users to be logged in simultaneously. Currently, users can log in successfully. However, upon refreshing the page, all users get logged in as the ...

Utilize the useState hook to update state when changes occur in the

I currently have a functional component that utilizes a useState hook. The values it holds are sourced from my redux store, and I aim to update the state with the new store state every time an action is dispatched. At the moment, I've manually set an ...

Here is a way to display the chosen option from a list using Angular Js

Seeking guidance on Angular.Js - I have a dropdown that successfully picks the selected data, but fails to display the selected value upon revisit. Is there a specific property I should set for this functionality? Snippet of my code: <select class=& ...