Yashpal Sindhav
Yashpal Sindhav

Reputation: 375

Get all element of same class and detect first element from that via jquery

I've dynamic structure where data is coming in below way. I want to filter all element with class name "My_data" and take first of it. in below code structure i want to get first "My_data" class element.

<div class="all_data">
<div class="listing">
    <div class="other_1">Block One</div>
    <div class="mbox">Block Two</div>
    <div class="other_2">Block Three</div>
    <div class="mbox">Block Four</div>
</div>
<div class="listing">
    <div class="other_1">Block One</div>
    <div class="mbox">Block Two</div>
    <div class="other_2">Block Three</div>
    <div class="mbox">Block Four</div>
</div>
<div class="listing">
    <div class="other_2">Block One</div>
    <div class="My_data">My data 1</div>
    <div class="other_2">Block Three</div>
    <div class="My_data">My data 2</div>
</div>
<div class="listing">
    <div class="other_5">Block One</div>
    <div class="My_data">My data 3</div>
    <div class="other_2">Block Three</div>
    <div class="My_data">My data 4</div>
</div>
</div>

so from above code structure I want to select My data 1

Please note: this data structure is dynamic so it might be change every time. sometimes first listing div get "My_data" class and some time no listing div has it.

Upvotes: 0

Views: 87

Answers (2)

JJWesterkamp
JJWesterkamp

Reputation: 7916

Try this:

var myDataDiv = document.querySelector('.My_data')
var myData = myDataDiff && myDataDiff.innerText; // > string | null

document.querySelector('.My_data') will either return the first element with class My_data - if it exists - or null otherwise. Therefore myData will either be null or the result of myDataDiff.innerText.

Upvotes: 1

Vipul Parmar
Vipul Parmar

Reputation: 11

Just make one empty div and append all child divs of listing class in it. After that take the first from that new list.

Upvotes: 1

Related Questions