Home > Software engineering >  How Do I Access An Element from Within Another Element?
How Do I Access An Element from Within Another Element?

Time:07-12

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 >
Object 1
<div >Black</div>
</div>
<div >
Object 2
<div >Brown</div>
</div>
<div >
Object 3
<div >Red</div>
</div>    

How would I access the hair for solely Object 3?

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

CodePudding user response:

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

CodePudding user response:

You can write the parents class before the child

const el = document.querySelector(".3 .hair")

CodePudding user response:

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 >
  Object 1
  <div >Black</div>
</div>
<div >
  Object 2
  <div >Brown</div>
</div>
<div >
  Object 3
  <div >Red</div>
</div>

  • Related