Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
How Do I Access An Element from Within Another Element?

I'm building a website and I need to access an element with a specific class name from another element but I have used this class name within other groups.

    <div class="1">
Object 1
<div class="hair">Black</div>
</div>
<div class="2">
Object 2
<div class="hair">Brown</div>
</div>
<div class="3">
Object 3
<div class="hair">Red</div>
</div>    

How would I access the hair for solely Object 3?

Could someone please provide a solution? Thank you so much!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

If you need to access this element with CSS, you can simply use the parent class.

.3 .hair{}

If you are trying to get this object in JS, you have two choices. The first one is to use vanilla js.

//+ES6
document.querySelector(".3 .hair").innerText;
//Red

//---------

//vanilla js
document.getElementsByClassName("3")[0].getElementsByClassName("hair")[0].innerText;
//Red

The second choice is jQuery. It's like using the query selector.

$(".3 .hair").text();
//Red
about 4 years ago · Juan Pablo Isaza Report

0

You can write the parents class before the child

const el = document.querySelector(".3 .hair")
about 4 years ago · Juan Pablo Isaza Report

0

You can use the parent class as they are unique:

.three > .hair

Please Note:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit

Demo:

let thirdEl = document.querySelector('.three > .hair');
console.log(thirdEl.textContent)
<div class="one">
  Object 1
  <div class="hair">Black</div>
</div>
<div class="two">
  Object 2
  <div class="hair">Brown</div>
</div>
<div class="three">
  Object 3
  <div class="hair">Red</div>
</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!