A Guide to Retrieving the First Child Element's Text with Jquery and a Class Selector

I want to extract the text from the first child small element inside a dynamically generated div. The structure looks like this:

<div class="NDateCount" style="display:inline-block">
     <!--Issue to solve-->
     <small style="display:none;" class="ng-binding">2017-07-08T12:44:10.367+06:00</small>
     <small ng-show="CountPostDate(post.timelineStrore.creationDate) < 2" style="color:#1ab394;" class="ng-binding"><i class="fa fa-clock-o"></i> 3 hours ago</small>
     <!--End of Issue to solve-->
</div>

I have multiple instances of this div being generated and I am trying to retrieve the content of the first small element using jQuery. So far, my code looks like this:

    var ReloadTime = function () {
        $('.NDateCount').each(function () {
            var OldValue = $(this).first().text();
            alert(OldValue);
         });
        setTimeout(ReloadTime, 50);
    }

However, this function is capturing the text from both small tags instead of just the first one as shown in this image:

Image link: https://i.sstatic.net/VOIFe.png

Is there a way to fix this issue?

Answer №1

Follow these steps

function RefreshData() {
    $('.NDateCount').each(function () {
        var PreviousValue = $(this).find('small').eq(0).text();
        console.log(PreviousValue);
     });
    setTimeout(RefreshData, 50);
}

This method is effective.

Answer №2

first() function retrieves the first div element, allowing you to access the text inside it.

To retrieve the first child of $(this), you can use the children method followed by first():

var OldValue = $(this).children().first().text();

var ReloadTime = function() {
  $('.NDateCount').each(function() {
    var OldValue = $(this).children().first().text();
    alert(OldValue);
  });
  //setTimeout(ReloadTime, 50);
}

ReloadTime();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="NDateCount" style="display:inline-block">
  <!--Issue to solve-->
  <small style="display:none;" class="ng-binding">2017-07-08T12:44:10.367+06:00</small>
  <small ng-show="CountPostDate(post.timelineStrore.creationDate) < 2" style="color:#1ab394;" class="ng-binding"><i class="fa fa-clock-o"></i> 3 hours ago</small>
  <!--End of Issue to solve-->
</div>
<div class="NDateCount" style="display:inline-block">
  <!--Issue to solve-->
  <small style="display:none;" class="ng-binding">2017-07-08T12:44:10.367+06:00</small>
  <small ng-show="CountPostDate(post.timelineStrore.creationDate) < 2" style="color:#1ab394;" class="ng-binding"><i class="fa fa-clock-o"></i> 3 hours ago</small>
  <!--End of Issue to solve-->
</div>

Answer №3

var UpdateTime = function () {
        $('.NDateCount').each(function () {
            var PreviousValue = $(this).find('small').first().text();
            alert(PreviousValue);
         });
    }

setTimeout(UpdateTime, 50);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="NDateCount" style="display:inline-block">
     <!--Issue to resolve-->
     <small style="display:none;" class="ng-binding">2017-07-08T12:44:10.367+06:00</small>
     <small ng-show="CountPostDate(post.timelineStrore.creationDate) < 2" style="color:#1ab394;" class="ng-binding"><i class="fa fa-clock-o"></i> 3 hours ago</small>
     <!--End of Issue to solve-->
</div>

In the code snippet above, it is important to note that the setTimeout() must be separate from the main function UpdateTime() for proper execution. It is also crucial to correctly reference elements within the loop using $(this) and find specific child elements like <small> to retrieve desired values.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Improperly positioned Divs overlapping

Help needed: I am attempting to add a menu to a specific section. The menu div is extending off the page to the right, but it should be contained within the HOMEMENU section (the long black bar with no content). Despite using a clear:both div, the menu s ...

Directing a controller assignment in AngularJS 1.2 via a directive

Transitioning from angularJS 1.0 to 1.2 has presented a challenge for me when it comes to assigning a controller to a directive with a distinct scope, without explicitly defining the controller in my HTML using ng-controller. Let's look at this scena ...

Is it possible to filter an array of data using a dropdown in Angular without using a pipe?

I am facing an issue with filtering data based on the selected dropdown item. Currently, it only filters the data once when I select a filter, and after that, it always returns an empty result. Here is an example of the code: <select class="select" (c ...

Is there a way to group together select values in a dropdown menu under a shared category?

If I have a dropdown menu that looks like for example: <select> <option value="1">1</option> <option value="3">3</option> <option value="2">2</option> <option value="4">4</option> </select&g ...

Steps for deleting a game objectWould you like to learn how to

What is the process of creating an object that can eliminate itself automatically? var item = []; function selfDestruct() { this.destroy = () => { this = false; } } function initialization() { item[0] = new SelfDestruct(); item[0].destroy( ...

When subscribed to, the BehaviorSubject will return the object twice

When working with a bank API for payments, the response expected by the banks is that Ban Pay JavaScript will perform an HTTP redirect in the top frame to a completeUrl. The question arises - what should be the completeUrl that I need to provide to the ban ...

Using Three.js to showcase 3 different slices of heatmaps within a 3D environment

I'm working on using Three.js to create a 3D representation of a matrix. Each 2D plane in the matrix should be displayed as a 2D heatmap. Here is an example of what I'm aiming for: https://i.sstatic.net/Kj5yb.png My current obstacle is figuring ...

steps to remove the border of the select box in MUI component

i am struggling to disable the border on the select box and change the color of the label text when focused or blurred i have attempted it but have been unsuccessful i am not very skilled at Mui component customization this is the image that i desire ht ...

Retrieving information from subscription

I am currently diving into Angular 2 and have successfully fetched data from my service. However, before displaying it on the view, I need to iterate over it using a for() loop. To achieve this, I have stored the fetched JSON data into an array. But I&apos ...

Timeout for browser response

Currently working on Perl CGI scripting within HTML, my script utilizes send expect and print statements. To prevent the browser from displaying the send expect results, I included $exp->log_user(0). When running the script in the browser, only the prin ...

Why is the v-for directive malfunctioning and am I correctly displaying it in the template?

I'm new to working with Vuejs and recently created a mock dataset using JSON. The JSON file consists of an array containing 3 objects. Although console.log shows that Axios.get(URL) is fetching the data correctly, the v-for directive doesn't seem ...

Place an overlay element in the top-left corner of a perfectly centered image

Currently, there is an image that is centered on the screen using flexbox: .center-flex { display: flex; justify-content: center; } <div class="center-flex"> <img id="revealImage"> </div> An attempt is be ...

Issue with the functionality of max-height in a CSS grid container

Update: After receiving clarification from @onkar-ruikar, I realized that my original problem was quite misunderstood. While I still haven't figured out how to properly handle the cyclic dependencies issue, I decided to address it separately. As a res ...

Magnific Popup - Overlook the images within the gallery

I am currently utilizing a combination of Slick Slider and Magnific on my website. The Slick slider is set to loop infinitely and displays multiple images within the gallery. The entire slider functions as one Magnific gallery. Since Slick creates cloned ...

Leverage the power of multiline JavaScript expressions within your React components

I am facing a situation where I have the following React function component source code: return ( result.map(item => ( <tr key={item.id}> <td> {new Date(item.pub_date).getFullYear()} / {new Date(item.pub_date).getMont ...

Executing a Parent Page JavaScript Method from Within an iFrame

I have included an iFrame in my application. To illustrate, consider the following example: The main page contains <html> <head> <script src='jquery.js'></script> <script> function TestFunction() ...

Incorporating date formatting to the existing documents

The mongoose schema I have created is structured in the following way. mongoose.Schema({ "url": String, "translations": [ { "targetLang": String, "source": String, ...

What's the best way to incorporate necessary styles into text using particular fonts?

Is there a way to set letter spacing and word spacing for text on my website with the font 'classylight'? Adding classes to each post in the site map seems like a lengthy process. To save time, I attempted to use the attribute*=style property to ...

Tips for effectively utilizing Mongoose models within Next.js

Currently, I am in the process of developing a Next.js application using TypeScript and MongoDB/Mongoose. Lately, I encountered an issue related to Mongoose models where they were attempting to overwrite the Model every time it was utilized. Here is the c ...

Transform static borders into mesmerizing animations by changing the solid lines to dotted lines using CSS

I've managed to create a circle animation that is working well, but now I'm looking to switch from solid lines to dotted lines. Can anyone provide guidance on how to accomplish this? Here is the current appearance: #loading { width: 50px; ...