Perform the same actions on every element within the ul li

I'm facing an issue with my unordered list, where each list item contains a span element with an image inside. My goal is to set the background-image of each span to be the same as the image it contains, while also setting the opacity of the image to 0.

Despite writing some code to achieve this, it doesn't seem to be working as expected. Even when I comment out the line that sets the background image, the images are still visible. This leads me to believe that there's an error in how the background image is being applied.

Could someone please help me understand what I'm doing wrong? Thank you!

var myUl = $('.my-ul');
  
    [...myUl.children].forEach(childLi => {
        const span_list = childLi.querySelector('span');
        const img_list = childLi.querySelector('img');
        var path_picture = img_list.src;
        $(span_list).css("background-image", "url(${path_picture})");
        $(span_list).css("background-size", "contain");
        img_list.style.opacity = 0;
  });
 .my-ul li span {
    display: block;
    width: 200px;
    height: 200px;
  }

  .my-ul li img {
    width: 100%;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul class="my-ul">
  <li>
    <span>
      <img src="https://www.trudellanimalhealth.com/sites/default/files/documents/tmdi-cat-athma-concern_2x.png" />
    </span>
  </li>
  <li>
    <span>
      <img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg" />
    </span>
  </li>
  <li>
    <span>
      <img src="https://undark.org/wp-content/uploads/2020/02/GettyImages-1199242002-1-scaled.jpg" />
    </span>
  </li>
</ul>

Answer №1

There are a couple of issues that need to be addressed:

  • $(".myul") returns a jQuery collection, which has a .children() function (not a property) but it is not an array and therefore cannot be iterated using [...].forEach
  • "url(${path_picture})" appears to use string interpolation, so it should use backticks ` instead of quotes "

The corrected code snippet would look like this:

//var myUl = $('.my-ul');
var myUl = document.querySelector(".my-ul");

[...myUl.children].forEach(childLi => {
  const span_list = childLi.querySelector('span');
  const img_list = childLi.querySelector('img');
  var path_picture = img_list.src;
  $(span_list).css("background-image", `url(${path_picture})`);
  $(span_list).css("background-size", "contain");
  img_list.style.opacity = 0;
});
.my-ul li span {
  display: block;
  width: 200px;
  height: 200px;
}

.my-ul li img {
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul class="my-ul">
  <li>
    <span>
      <img src="https://www.trudellanimalhealth.com/sites/default/files/documents/tmdi-cat-athma-concern_2x.png" />
    </span>
  </li>
  <li>
    <span>
      <img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg" />
    </span>
  </li>
  <li>
    <span>
      <img src="https://undark.org/wp-content/uploads/2020/02/GettyImages-1199242002-1-scaled.jpg" />
    </span>
  </li>
</ul>

An alternative approach would be to utilize jQuery as demonstrated below:

var myUl = $('.my-ul');

myUl.children().each((i, e) => {
  var path_picture = $("img", e).attr("src");
  $("span", e)
      .css("background-image", `url(${path_picture})`)
      .css("background-size", "contain");
  $("img", e).hide();
});
.my-ul li span {
  display: block;
  width: 200px;
  height: 200px;
}

.my-ul li img {
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul class="my-ul">
  <li>
    <span>
      <img src="https://www.trudellanimalhealth.com/sites/default/files/documents/tmdi-cat-athma-concern_2x.png" />
    </span>
  </li>
  <li>
    <span>
      <img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg" />
    </span>
  </li>
  <li>
    <span>
      <img src="https://undark.org/wp-content/uploads/2020/02/GettyImages-1199242002-1-scaled.jpg" />
    </span>
  </li>
</ul>

Answer №2

When it comes to adjusting styles in vanilla js or jquery, there could be an issue with the code img_list.style.opacity = 0;. It's possible that img_list represents a collection of elements or nodes which is causing the code to not function as expected.

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

How can the parameters -i -u "clientId:" be interpreted when translating a curl command into Ajax?

As I work on integrating a 3rd party API into my website, I am currently in the testing phase using Postman (the Chrome Extension) before proceeding to write my AngularJS Service with $http. However, there is one aspect of the process that has me puzzled. ...

Instead of logging the JSON file in the console, download it using $.getJson()

Is there a method to download a json file without using jQuery's $.getJSON() and having to log the callback function's argument? I would like to avoid manually typing it from the console.log due to its length. Is there an option to print it, eve ...

The Javascript document refuses to load

I am currently working on a website with the main file named index.html: <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Title</title> </head> ...

propagate the previous state using a variable

Currently, I am in the process of refactoring a codebase but have hit a roadblock. My main aim is to update the state when the onChange event of a select box occurs. Specifically, the parameter searchCriteria in my handleFilterChange function is set to in ...

Improprove Google PageSpeed score - must resolve

My mobile website is loading incredibly slow, despite my attempts to improve the speed using Google PageSpeed insights. Unfortunately, I'm having trouble interpreting the screenshot and identifying what changes need to be made. Is there anyone who c ...

The conflict between Material UI's CSSBaseline and react-mentions is causing issues

Wondering why the CSSBaseline of Material UI is causing issues with the background color alignment of React-mentions and seeking a solution (https://www.npmjs.com/package/react-mentions) Check out this setup: https://codesandbox.io/s/frosty-wildflower-21w ...

Unable to interpret Python/Django-generated JSON object on client side

I'm encountering an issue while passing a data object from a Python/Django application to the frontend using AJAX in JSON format. Despite everything appearing to be functioning correctly, I am unable to properly parse the JSON object within JavaScript ...

How to Implement Jquery Confirm in Laravel Form Opening?

I've set up a Form using the Laravel Form package. {!! Form::open(['action' => ['Test\\BlogController@destroy', $thread->id], 'method' => 'delete', 'onsubmit' => 'Confirm() ...

What steps should I take to execute a task during input checkout?

Check out my code below: $(document).on('checkout', 'input', function(){ alert('input is not focused anymore'); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <i ...

Disappearing Act: The vanishing act of Bootstrap 4 navbar

Everything works perfectly on a large screen, but disappears when resizing. I haven't specified a height property for the navbar. Here's the Fiddle. I know this question has been asked many times before, but I have yet to find a solution that act ...

Redux's 'connect' function fails to recognize changes in the state array

I've recently implemented redux with a reducer that handles an array of time slots for a specific date. Whenever the date is changed, the reducer successfully updates the state (confirmed through console logs in my mapStateToProps function). However, ...

Implementing the display of bootstrap modal with error message upon page reload in CodeIgniter

Currently, I have a popup model that allows users to add a course name. In my Codeigniter controller, I have implemented form validation. If the validation fails, I reload the view with an error message displayed above the form input in the modal. However, ...

Leveraging Ajax and jQuery to create a POST request for adding a new record to a MySQL table within a Node.js server

My form is designed to collect user information like name, age, and more. The aim is to submit this data from the client side, inserting it into a MySQL table row. However, I'm facing difficulties in getting the data to successfully insert. Below are ...

Having difficulty with printing a particular div

I need help with printing a specific div containing checkboxes using jQuery. The checkboxes are initially checked based on data from a database, but when I try to print the div, the checkboxes remain unchecked in the print view. Below is the code snippet ...

Utilizing variables in GraphQL requests

UPDATE: see the working code below GraphiQL Query I have this query for retrieving a gatsby-image: query getImages($fileName: String) { landscape: file(relativePath: {eq: $fileName}) { childImageSharp { fluid(maxWidth: 1000) { base64 ...

Is it possible to dynamically assign and call functions through an Object in Angular 6?

I implemented a click handler for a button that is generated dynamically. Within the click handler function, I am invoking a callback function. However, I encountered an issue where an error message popped up stating that "Callback function is not a fu ...

Update and republish an outdated npm package

After successfully publishing an npm package, I attempted to make an update which unfortunately resulted in some issues. It seems that I made a mistake during the build process. Since it had been a year since my last update, I have forgotten the exact step ...

AWS Lambda optimizes variable initialization by reusing values from previous executions, eliminating the need to reinitialize

Currently, I am encountering a problem while deploying an AWS Lambda Function for numeric calculations. The issue arises when the function is initially deployed and runs correctly, but subsequently it starts taking previous values into account and recalcul ...

Tips for activating this effect even when the window is resized during page scrolling

There's a code snippet that enables the header to become unfixed when a specific div reaches the top of the screen and then scrolls with the rest of the content. While this solution works perfectly, I encountered a problem where the calculations for ...

Incorporating Only XSD Files into an HTML Input Tag: A Simple Guide

Is there a way to restrict a file input element to only display XSD files? I attempted the following: <input type="file" accept="text/xsd" > Unfortunately, this method is not working as it still allows all file formats to be disp ...