Struggling to navigate the DOM using JavaScript and looking for guidance?

I have been searching for an answer to this question without any luck. I am wondering if someone can assist me with finding a solution...

I need help using JavaScript (not jQuery) to retrieve the class of the following li element when searching for 'Chicken' or any other specified value.

<li class='113252'>
    <span>Chicken</span>
</li>

I would like the JavaScript code to return the class of the li element based on the span value provided (in this case, Chicken).

Thank you in advance!

Answer №1

Give this a try:

var spanArray = document.getElementsByTagName('span');

for (var i=0; i<spanArray.length; i++) {
    if(spanArray[i].innerHTML.toUpperCase() === 'CHICKEN')
    {
        alert(spanArray[i].parentNode.className);
        break;
    }
}

While I usually work with jQuery, the code above seems to function well in the provided fiddle: http://jsfiddle.net/FranWahl/fCzYc/2/ (Updated with suggested break; after match)

You can enhance type checking for the parentNode to ensure it is an li and so on, but this should give you a good starting point.

As for efficiency in larger documents, that's something I'm not entirely sure about.

Edit
After reviewing some comments, I have updated my code above to include the recommended break by ajax333221.

Dennis suggested that it would be better to call getElementByTagName on the ul. Since you may have an li without a ul, I separated this code as I am unsure if there are ul tags present in the OP's scenario.

Code for querying against each ul (jsFiddle here)

var ulArray = document.getElementsByTagName('ul');
var parentFound = false;

for (var i = 0; i < ulArray.length; i++) {
    var spanArray = ulArray[i].getElementsByTagName('span');

    for (var i = 0; i < spanArray.length; i++) {
        if (spanArray[i].innerHTML.toUpperCase() === 'CHICKEN') {
            alert(spanArray[i].parentNode.className);
            parentFound = true;
            break;
        }
    }

    if(parentFound)
    {
        break;
    }
}​

Answer №2

Although not fully comprehensive, this code snippet serves two main purposes:

  1. It recursively scans through child elements (starting with the document's BODY) to locate the specified text.
  2. It also recursively examines the parent element to identify the specified parent element tag; once found, it retrieves the class of that parent.

To view the JSFiddle demonstration, visit: http://jsfiddle.net/vol7ron/bttQN/

function getParentClass(element, parentTag){
   if (element.tagName == parentTag.toUpperCase())
       return element.className;
   return getParentClass(element.parentNode,parentTag);
}

window.findParentClass = function (text,tagName){
    var elements = document.getElementsByTagName('body');
    for (var n=elements.length; n--;){
        var foundClass = (function searchNextChild(el){
            if (!el.children.length) {
                if (el.textContent == text) 
                   return getParentClass(el,tagName);
                return;
            }
            for (var i=0, n=el.children.length; i<n; i++)
               return searchNextChild(el.children[i]);
        })(elements[n]);

        return foundClass;
    }
};

Example Usage:

alert( findParentClass('Chicken','li') );

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

Introducing additional choices to the list and automatically refreshing the list with the latest updates

I am currently honing my skills in Yii2 by working on a project using this framework. One of the challenges I am facing is adding new list options dynamically without having to navigate away from the current page. When I click the "Add new option" button ...

Protractor: Configuration file failed to load

Upon the installation of protractor and initiation of selenium webdriver, I encountered an issue while attempting to run the config.js file located in the example folder of protractor. The error message "ERROR loading configuration file config.js" is displ ...

Enriching an array with values using Mongoose

Is there a way to assign a User as an admin for the School? School Schema: const School = new Schema({ name: { type: String, required: true }, grades_primary: [{ type: Schema.Types.ObjectId, ref: 'Grade' }], grades_secondary: [{ type ...

Enhance Your Vue Tables with Unique Custom Filters

I'm currently working on implementing https://github.com/matfish2/vue-tables-2 in Vue 2.1.8. Everything seems to be functioning flawlessly, but I need to incorporate custom filters to format certain fields based on their values. In my options object ...

I want to display events from my database table on their corresponding dates using JavaScript and jQuery. How can I achieve this?

Using the FullCalendar plugin, I attempted to achieve a specific functionality, but unfortunately fell short of my goal. Below is the snippet of my scripting code: $('#calendar').fullCalendar({ //theme: true, header: { ...

Prevent identical values from being added repeatedly to a table while updating in real-time

Currently, I am facing an issue while running through a loop to extract values from an array. When I add a second value, it duplicates both the new and previous values in the table. For example, adding a row with value 488 works fine: <tr class="exe"& ...

Customizing Django forms.Textarea in template or declaring in models is essential for creating a unique

Within my models, I have a forms.Form that includes a textarea field: answer1 = forms.CharField(label='Answer 1', widget=forms.Textarea(attrs={"placeholder":"Type your answer...", "rows":6, "cols":45}), max_length=150) When it comes to views: ...

Exhilarating Javascript document with fresh lines and line breaks

In my current project, I am dynamically generating a JavaScript page using PHP and .htaccess to convert .php files into .js files. Everything is functioning properly, except for the output of the JavaScript code. For example: $data = array('one&apo ...

Update the array state based on the selection of checkboxes and user input in real-time

In my current project using react js, I am working on a UI development task where I need to create a dynamic table based on data fetched from an API. Each row in the table includes a checkbox and a text input field that are dynamically generated. My goal i ...

Is there a way to showcase individual components on a single surface one at a time?

Let me try to explain my issue as clearly as possible! I am currently working on a website using React and Material-UI. On one of my pages, I have a Paper component where I want to display different components that I have created, but only one at a time. ...

The value of an AngularJS service is not being reflected in the view

I have implemented the stateProvider in my code, and I am facing an issue with updating the breadcrumbs in the header when the state changes. Instead of creating embedded views for each state, I have a service that shares an array of breadcrumbs containing ...

Modify the image source using Javascript

I need to update the src attribute of an image in a parent element nested within a ul li when a link is clicked. Here's my code so far. I know how to use JavaScript to change the src attribute, but I'm not sure how many levels I need to go up to ...

What is the best way to turn off the legends in chart.js?

I'm having trouble customizing a chart using chart.js because I can't seem to disable the legends within the canvas element. However, I still want to style the legends elsewhere on the page using generateLegend(). Can anyone provide assistance wi ...

Transferring hyperlink text to a different page using Express JS

I'm currently dealing with a coding issue where I need to pass a link text within a hyperlink to another page. The web application is built using Express. On one of the pages, there's a dropdown list containing this hyperlink: <a class=" ...

Is it possible to utilize Vue's splice method within a forEach loop in order to delete multiple elements at

I am currently working on an image grid in array form. I am trying to implement a multi-deletion functionality. When a checkbox for each image in the grid is checked, I store the selected image's index in an array called selectedImages. Upon clickin ...

Issue encountered while compiling ReactJs: Unexpected token error found in App.js

I executed the commands below. npx create-react-app github-first-app npm install --save react-tabs npm i styled-components npm install git-state --save using the following code files App.js import React from "react"; import Layout from " ...

In my Laravel Vue JS project, every Put and Delete route method triggers a 302 error

I'm encountering an issue with my Laravel Vue JS application where the PUT and DELETE methods are throwing a 302 error. Here is the response from my localhost: And this is the response from my server: While everything works perfectly on my lo ...

Encountering issues while attempting to transmit several files to backend in React/NestJS resulting in a BAD REQUEST error

My goal is to allow users to upload both their CV and image at the same time as a feature. However, every time I attempt to send both files simultaneously to the backend, I encounter a Bad Request error 400. I have made various attempts to troubleshoot th ...

What is the optimal location for storing component fetch logic?

When should I make a REST request to retrieve data for a Vue component called Page, specifically for the properties title and content? Also, where is the best place to handle this logic? Currently, I am trying to fetch the data on the component's rea ...

Steps for adjusting the position of this div in relation to the main container

Apologies in advance for my lack of HTML skills. I am struggling with a page layout issue. I have a website at . When the window is resized, the ads div on the right side overlaps the main container. What I would like to achieve is to make this ads div re ...