0

Here's my HTML format.

<div id="myid">

    <div class="first-class">

    </div>
    <div class="second-class">

    </div>
    <div class="third-class">

    </div>

</div>

What I want to achieve is find the third-class using the myid. How to achieve that? Thank you sir!

Kean Allen
  • 23
  • 1
  • 10

3 Answers3

2

You can use the find method.

$('#myid').find('.third-class')

OR

$('#myid .third-class')

OR

$('#myid').children('.third-class')

OR

$('.third-class', '#myid')
Tushar
  • 85,780
  • 21
  • 159
  • 179
1

You can use pure JavaScript something like

var thirdElem = document.getElementById('myid').getElementsByClassName("third-class")[0];

First we search the particular element by it's id ('myid') and we find the particular element by class ('third-class') inside the element ('myid').

OR

You can use querySelecotr, something like,

var thirdElem = document.querySelector('#myid .third-class');

In this case querySelector fetches the first element with class .third-class from div(#myid).

Suman Bogati
  • 6,289
  • 1
  • 23
  • 34
  • thank you bro!!! it's worked for me.can you kindly explain the purpose of [0] in getElementsByClassName – praveenkumar Aug 09 '18 at 12:36
  • `getElementsByClassName()` returns the array of node element, by doing `[0]` we are getting the first element from that array. However in above case, there would be the single element of array. – Suman Bogati Aug 10 '18 at 15:12
1

Or, if trying to find the third element regardless of class name, something like this:

$('#myid').children().eq(2)

(It's '2' since the index is zero-based), as example:

var className = $('#myid').children().eq(2).attr('class');
// className would be 'third-class'
Ted
  • 14,757
  • 2
  • 41
  • 58