Search code examples
javascriptjqueryhtmljquery-selectorsjquery-filter

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.


Solution

  • 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.