Get to a certain nested div by using jQuery

Can someone assist me in accessing a specific element within a div while using a foreach loop?

Below is the code snippet:

HTML

<div class="row menu-filter-items">
    <div class="col-md-4 margin-b-30 menu-item">
        <a href="#" class="menu-grid">
            <img src="images/img-1.jpg" alt="" class="img-fluid"/>
            <div class="menu-grid-desc">                               
            <!--  <span class="price float-right">$9.50</span> -->
                <h4 class="a" id="title">Restaurant y</h4>
                <p>
                    Description
                </p>
            </div>                           
        </a>
    </div>
</div>

Jquery:

 $('#search').keyup(function(e){
     var current_query = $('#search').val();
         if(current_query != null)
         {
             $("div.menu-filter-items").hide();
             $("div.menu-filter-items div.menu-item").each(function(){
                 var current_keyword = $(this).children('#title').text();

                 alert(current_keyword);
                 if (current_keyword.indexOf(current_query) >=0)
                 {
                     $("div.menu-filter-items").show();         
                 }

             });


         }
         else
         {
             $("div.menu-filter-items").show();
         }

});

I'm struggling to access the H4 tag, any assistance would be greatly appreciated. Thank you.

Answer №1

Opt for

let keyword = $(this).find('#title').text();

in place of

let keyword = $(this).children('#title').text();

Answer №2

To locate elements, it's recommended to utilize the find function.

When using the .children() method, we are able to explore the children within the DOM hierarchy and form a new set of elements using jQuery. It's important to note that the .children() method functions differently from .find() as it only digs one level deep into the DOM tree, whereas .find() can delve into multiple levels for selecting descendant elements as needed.

Answer №3

Utilize the find method in JQuery to conduct searches within the library.

To access the comprehensive documentation, click on this link: https://api.jquery.com/find/

In your scenario, you can use:

$( "section.item-container" ).find( "p.description" )

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

Guide on transferring control from a successful jQuery event to an HTML form

I am currently using the following jQuery code to validate user details. $.ajax({ type: "POST", url: "Login", data:'uname='+encodeURIComponent(uname)+'&'+'pass='+encodeURIComponent(pass), ...

Patience is key: techniques for real-time variable updates and calculations in JavaScript

Hi, I am currently working on creating a dashboard to calculate the total outstanding amount for my medicine suppliers using Next.js. Below is the code snippet for my "createPurchase" API: import PurchaseOrder from '../../models/PurchaseOrder' ...

Vue-resource is returning a Promise object

How do I access the response data in an Ajax call? When I log response.text(), it displays a PromiseObj. Console PromiseObj context: undefined promise: Promise {status: "resolved", result: ")]}',↵{\"Result\":\"SUCCESS\",&bs ...

Passing the AngularJS ng-model from a template to a directive's controller

I have created a directive with a controller that is responsible for building a form to post comments to an API through CommentsService Here is a snippet of how my directive looks: app.directive('appComments', function( CommentService ) { r ...

How can I store the value of `$_POST['data']` in a jQuery variable?

Upon receiving data from a form on a new page, the code looks like this: $id = $_POST['id'] $date = $_POST['date'] The use of jQuery and ajax to process the posted data from the previous page and display it on the current page where ...

Folding animation using CSS3 and vertex manipulation

Looking to create a folding animation on a squared div with vertex? While there are examples online using Flash, I'm seeking guidance on how to achieve a similar effect using CSS3 and HTML5. Any tips or resources would be greatly appreciated. Thank y ...

Exploring Attachments in ASP.NET Core MVC Views

I have placed attachments in a Shared Folder on a server. I attempted to access them using the <a> tag <a href="file:///C:">Open Attachments</a> Unfortunately, this method did not work in ASP.NET Core MVC for unknown reasons. I ...

What are your thoughts on using inline PHP to assign values to JavaScript variables?

Imagine you have a PHP document and need to determine if the request was made with or without query parameters using JavaScript. Since there is no built-in function to extract values from the URL, you may need to resort to some sort of workaround. While it ...

Interacting with a card in vuejs won't trigger any action

Is there a way to make an overlay disappear when clicking anywhere on the screen except for a specific card positioned on top of it? The current setup makes the overlay disappear even when the card is clicked. How can this behavior be corrected? <div ...

What is the best way to designate external dependencies in WebPack that are not imported using '*'?

I need assistance with specifying office-ui-fabric-react as an external dependency in my TypeScript project using Webpack. Currently, I am importing only the modules I require in my project: import { Dialog, DialogType, DialogFooter } from 'office-u ...

Tips on concealing error messages and displaying only a single error message using jQuery validation

I am currently utilizing the jQuery Validate Plugin to validate my form inputs. My goal is to hide the error messages displayed next to the input fields and instead show a main error message at the bottom of the form. While I have managed to achieve this t ...

Parsing of CSS and Javascript is disabled within iframes

Within my node.js application, I have configured an endpoint where I can load some parsed HTML code. This is achieved through the following code: app.get('/code', function (req, res) { res.setHeader('Content-Type', 'text/html& ...

Having trouble positioning items to the right in bootstrap

<div id="unique-content-wrapper"> <nav class="navbar navbar-expand-lg navbar-light bg-light" id=""> <button class="navbar-toggler" id="menu-toggle"><span class="mater ...

The World of JavaScript Frameworks

Seeking clarification on nodejs web frameworks. Recently began exploring express js on free code camp and have a few questions. Is express a full stack framework or just for backend development? I've noticed you can integrate various templating engine ...

Error Handling with Firebase Cloud Firestore and State Management in Vue using Vuex (firebase.firestore.QuerySnapshot)

Upon examining the code, I noticed an issue with docChanges. It seems to be a function, but when I try to use docChanges().doc.data().userId, I encounter the error message: store.js?3bf3:21 Uncaught TypeError: Cannot read property 'doc' of undefi ...

Transmitting a pair of data points to PHP using ajax POST for querying the SQL database

I am attempting to send two values from a form to another PHP file using the ajax post method. One value is the current input box value, while the other is the value being typed into a different input box which functions as a search box. When I execute the ...

Issues with maintaining the checked state of radio buttons in an Angular 4 application with Bootstrap 4

In my Angular 4 reactive form, I am struggling with the following code: <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary" *ngFor="let item of list;let i=index" > <input type="radio" name="som ...

Attempting to ensure that my website is fully optimized for all devices and

I am currently facing an issue with my CSS code on iPad. I want to change the background-image displayed based on whether the user is using an iPad or not. Specifically, I want to use headerold.jpg as the background-image for iPads while keeping headernew. ...

Send the array of data to the table in a separate component

I am currently working on developing a basic online shop using React. For testing purposes, I have not integrated it with any API or database yet. Instead, I am utilizing an array of data to display items on the homepage. My goal is to enable visitors to a ...

Issues with style not loading properly within innerHTML in Angular2

Currently, I am in the process of developing a page using Angular2/4 that includes a left navigation bar. To achieve reusability, I have separated this left menu into its own component and nested it within the main component. The objective is to utilize th ...