Controlling the <li> tag within the <ul> tag using JavaScript

Here's the code snippet I'm working with:

<div style="background-color:red;">
   <ul class="myClass">
      <li> CCD </li>
      <li class="active"> BCA </li>
      <li> ABC </li>
   </ul>
</div

I am trying to automatically change the background color of the div when the class "active" is present. How can I target the li class when I only have the class for the ul element, and how can I use JavaScript to change the background color of this div?

Answer №1

To achieve this effect, you can utilize the jQuery :has() pseudo-class selector.

$('div:has(li.active)').css('background-color', 'green')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="backgroundColor='red'">
  <ul class="myClass">
    <li>CCD</li>
    <li class="active">BCA</li>
    <li>ABC</li>
  </ul>
</div>


Alternatively, you can also employ the filter() method in jQuery.

$('div').filter(function() {
  return $('li.active', this).length;
}).css('background-color', 'green')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="backgroundColor='red'">
  <ul class="myClass">
    <li>CCD</li>
    <li class="active">BCA</li>
    <li>ABC</li>
  </ul>
</div>


If you prefer using pure JavaScript, you can accomplish the same functionality with code like this.

// Select all elements and convert them into an array
// for iteration
Array.from(document.querySelectorAll('div'))
  // Iterate over the elements
  .forEach(function(ele) {
    // Check if specific element exists inside
    if (ele.querySelector('li.active'))
      // If it does, add a background color
      ele.style.backgroundColor = 'green';
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="backgroundColor='red'">
  <ul class="myClass">
    <li>CCD</li>
    <li class="active">BCA</li>
    <li>ABC</li>
  </ul>
</div>

Answer №2

$(document).ready(function(){
  $("ul.myClass li.active").closest("div").css("background-color", "green");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="backgroundColor='blue'">
  <ul class="myItems">
    <li>DDD</li>
    <li class="active">EFG</li>
    <li>GHI</li>
  </ul>
</div>

Answer №3

To begin with, there seems to be an issue with your css--it needs to be

<div style="background-color: red">

Following that, (using jQuery):

$('ul.myClass li.active').css('background-color', 'blue');

Check out the JSFiddle demo here

Answer №4

if($(".myClass li").hasClass("active")){
  $("div").css("background","red");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div style="backgroundColor='red'">
  <ul class="myClass">
    <li>XYZ</li>
    <li class="active">DEF</li>
    <li>GHI</li>
  </ul>
</div>

Answer №5

Utilizing pure vanilla JavaScript

var divs = document.getElementsByTagName("div")

for (var i = 0; i < divs.length; i++) {
 // accessing all child nodes within div elements
 var children = divs[i].getElementsByTagName("*");
 
 for (var j = 0; j < children.length; j++){
  if(children[j].className === "active"){
    children[j].style.backgroundColor = 'blue';
  }
 }
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="backgroundColor='red'">
  <ul class="myClass">
    <li>CCD</li>
    <li class="active">BCA</li>
    <li>ABC</li>
  </ul>
</div>

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

Tips for decreasing the file size without compromising the clarity of the image?

Currently, I am working on an image puzzle project using jQuery. Everything is almost complete, except for one issue: when the user selects the 2x2 puzzle, the cropped image size appears too large (the original cropped size). I need to reduce the size of t ...

Is it feasible to extract the Json object from its current location within another object?

Is there a way to manipulate this JSON data? "forms": [ { "_id": "Untitled Form", "title": "Untitled Form", "answer": [ { "username&quo ...

The issue arises when attempting to display a Google slideshow through ajax, resulting in only a

I'm facing issues with integrating a Google slideshow (http://www.google.com/uds/solutions/slideshow/index.html) into my web application by using a jQuery load() function. index.html: <script type="text/javascript" src="jquery-1.3.2.js"></s ...

Styling for dropdown menu button

I'm encountering an issue with a button styled dropdown. Here is the code snippet: <template> <div class="datatable-wrapper"> <div class="table-container"> <table class="table datatable-table i ...

Generating unique ID's for data posting in PHP and JavaScript

I've developed a dynamic form that includes an "add more" button to generate an XML file for data import purposes. Users can fill out the form and add as many entries as needed by clicking on the "add more" button. The inputted data is then processed ...

Determine the specific assertions that have caused the protractor test to fail

Is it possible to identify the specific test that failed when a protractor test fails? For instance, if the output only shows: 1 test, 1 assertion, 1 failure When there are multiple assertions and failures, identifying which one failed can be challengin ...

Tips for populating web view fields on Android using a combination of Java and JavaScript

Encountering an issue while attempting to populate fields in my android web view. Consistently receiving this error message 01-28 05:06:22.980: E/Web Console(2827): Uncaught TypeError: Cannot set property 'value' of null at null:1 Despite search ...

Ways to efficiently populate several dropdown menus with jQuery by making a single request to a local JSON file

I am running into an issue with the Country/City dropdowns in my project. Every time I try to change the countries, I encounter an unexpected behavior. How can I efficiently fetch the local JSON file to populate multiple dropdowns with just one request? Ta ...

Gather a variety of data inputs from a <select> tag and store them in a String array

Within my spring application, there is an html form that includes a select element which needs to pass values to the server. The code in the JSP page responsible for sending these values to the server is as follows: HTML Form <form name="form_lista_h ...

Conflicting styles arise when using the makeStyles function from Material UI with imported

In working on a React component library using create-react-library, I have incorporated basic components that utilize Material UI components and the material UI hook-based styles pattern. For example (in a simplified form): // LibraryComponent.js const u ...

Trouble arising when attempting to add or remove classes using JavaScript

I've been trying to use JavaScript to toggle the visibility of contact_form_top by adding or removing the hidden class when the button contact_form_btn is clicked, but I'm having trouble getting it to function properly. function hide_unhide_btn( ...

Coordinating Angular to communicate with Node.js to send and receive data

I am currently working on a project using express.js, but I would like to integrate angular into the project to create a single page application. The website currently refreshes the entire content from the server whenever a link is clicked, which seems ine ...

Converting JavaScript code for Angular: A step-by-step guide

I have been working on integrating a feature similar to the one demonstrated in this Angular project: https://codepen.io/vincentorback/pen/NGXjda While the code compiles without any issues in VS code, I encountered two errors when attempting to preview it ...

Having trouble with the Bootstrap dropdown? The unordered list isn't dropping down as expected. What could be the issue?

I am facing an issue with two dropdowns in my template. Both of them are not functioning properly, one with Thymeleaf attributes and the other without. I have not attempted to change the CSS properties as they were working fine before but now they do not ...

Struggling to retrieve information from a connected SQL table within an Express application

I am currently working on an API using express and postgreSQL to showcase restaurant ratings, reviews, and cuisine in specific areas. I have successfully created routes and controllers that display SQL tables in Postman. My challenge arises when attemptin ...

Ways to eliminate numerous if statements in JavaScript programming

Here is the code snippet I'm working with: a = [] b = [] c = [] useEffect(() => { if(isEmpty(a) && isEmpty(b) && isEmpty(c)) { data.refetch() } if(data.isFetching){ //do something } if(response.isFetching){ //do som ...

Tips for implementing next-iron-session with personalized api route middleware in NextJS?

Currently, I am working on implementing session storage with next-iron-session and using Firebase for authentication. Every API route requires both the auth middleware and next-iron-session. This is my first time using NextJS and I have tried several appro ...

What is a creative way to incorporate async/await in a React function to display a dialog box?

I'm currently working on an app utilizing react-modal. While it effectively brings up a dialog, I find that embedding the dialog component in the parent form scatters the code around the parent component. Therefore, I am interested in having all the ...

How can you extract path information from an SVG file and utilize it as a marker on Google Maps?

I want to implement a custom SVG icon as a marker on Google Maps. I have obtained this SVG file: <svg xmlns="http://www.w3.org/2000/svg" width="510px" height="510px" viewBox="0 0 510 510"> <g stroke="black" stroke-width="10" ...

Is there a way to automatically trigger the opening of a Popper upon initial page load?

Discovering the wonders of React and material-ui through https://material-ui.com/components/popper/, I am eager to showcase the Popper without requiring a button click once the page loads. import React from 'react' import Popper from '@mate ...