Conceal a single container without concealing everything else

Is there a way to hide an entire <div> if a profile image is missing, while keeping the other <div> with the same class visible? I've tried creating a solution in my jsfiddle, but I'm not sure if it's correct. Can someone verify?

I need this functionality to be implemented within the CSS/JS page of a closed system (Springshare/LibGuides), so I can't include any inline calls or similar methods.

$(() => {
  var src = $('img').attr('src');
  if (src === '//libapps.s3.amazonaws.com/apps/common/images/profile.jpg'){
    $('.s-lib-featured-profile-container').hide();
    } 
  else {
    $('.s-lib-featured-profile-container').show();
  }
})
<div class="s-lib-featured-profile-container"><a href="/prf.php?account_id=127256">
    <div class="s-lib-featured-profile-image">
      <img src="//libapps.s3.amazonaws.com/apps/common/images/profile.jpg" alt="Julie Brewer's picture">
    </div>
    <div class="s-lib-profile-div s-lib-featured-profile-name">Julie Brewer</div></a>
</div>
 
 
 
<div class="s-lib-featured-profile-container"><a href="/prf.php?account_id=131922">
    <div class="s-lib-featured-profile-image">
      <img src="//libapps.s3.amazonaws.com/accounts/131922/profiles/125264/Caldwell_John.jpg" alt="John Caldwell's picture">
    </div>
    <div class="s-lib-profile-div s-lib-featured-profile-name">John Caldwell</div></a>
</div>

For more information, please refer to the jsfiddle example:

https://jsfiddle.net/Raser/nq5swa10/3/

The goal is for the code to utilize the img and src attributes to hide the

<div class="s-lib-featured-profile-container">
containing "Julie Brewer" and show the one containing "John Caldwell".

Thank you for any help!

Answer №1

To achieve the desired result, iterate through all the div elements containing the specific image you are looking for. Keep in mind that the browser appends the current scheme to URLs starting with //, so consider using a method like endsWith in your search.

$(() => {
  $(".s-lib-featured-profile-container").each((index, container) => {
    var src = $(container).find('img').prop('src');
    console.log(src);
    if (src === 'https://libapps.s3.amazonaws.com/apps/common/images/profile.jpg') {
      $(container).hide();
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>

</head>

<body>


  <div class="s-lib-featured-profile-container">
    <a href="/prf.php?account_id=127256">
      <div class="s-lib-featured-profile-image">
        <img src="//libapps.s3.amazonaws.com/apps/common/images/profile.jpg" alt="Julie Brewer's picture">
      </div>
      <div class="s-lib-profile-div s-lib-featured-profile-name">Julie Brewer</div>
    </a>
  </div>



  <div class="s-lib-featured-profile-container">
    <a href="/prf.php?account_id=131922">
      <div class="s-lib-featured-profile-image">
        <img src="//libapps.s3.amazonaws.com/accounts/131922/profiles/125264/Caldwell_John.jpg" alt="John Caldwell's picture">
      </div>
      <div class="s-lib-profile-div s-lib-featured-profile-name">John Caldwell</div>
    </a>
  </div>



</body>

</html>

Answer №2

You have chosen to hide all the images at once, rather than going through each image individually to determine if it should be hidden.

$(() => {
  var allItems = $('.s-lib-featured-profile-container');
  allItems.each(function(){
    var image = $(this).find('img');
    if (image && image.attr('src') === '//libapps.s3.amazonaws.com/apps/common/images/profile.jpg'){
      $(this).hide();
    }
  });
})
img{
 width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="s-lib-featured-profile-container"><a href="/prf.php?account_id=127256">
    <div class="s-lib-featured-profile-image">
      <img src="//libapps.s3.amazonaws.com/apps/common/images/profile.jpg" alt="Julie Brewer's picture">
    </div>
    <div class="s-lib-profile-div s-lib-featured-profile-name">Julie Brewer</div></a>
</div>
 
 
 
<div class="s-lib-featured-profile-container"><a href="/prf.php?account_id=131922">
    <div class="s-lib-featured-profile-image">
      <img src="//libapps.s3.amazonaws.com/accounts/131922/profiles/125264/Caldwell_John.jpg" alt="John Caldwell's picture">
    </div>
    <div class="s-lib-profile-div s-lib-featured-profile-name">John Caldwell</div></a>
</div>

Answer №3

To filter out image containers containing a default picture, consider using the JQuery method .filter instead of .each. Once identified, simply hide them using .hide.

Code:

var with_default_profile = $(".s-lib-featured-profile-image")
  .filter(function() {
    return $(this).find("img")
    .attr("src") === "//libapps.s3.amazonaws.com/apps/common/images/profile.jpg";
  })
  with_default_profile.hide();

Code With Comments:

// find all image containers

var with_default_profile = $(".s-lib-featured-profile-image")

// filter image containers by checking
// if they have an img with src ".../jpg"

  .filter(function() {
    return $(this).find("img")
    .attr("src") === "//libapps.s3.amazonaws.com/apps/common/images/profile.jpg";
  })

// hide images that meet the criteria

  with_default_profile.hide();

Advantages of Using filter Over each:

Filter enhances code readability and extensibility. It clearly indicates that filtering is taking place rather than simple iteration.

Comparing filter and each:

The choice between filter and each is subjective. While each iterates over the list once to hide elements, filter/hide first iterate and then hide each element individually, possibly impacting performance slightly. However, the difference in performance is likely minimal. The preference for filter or each depends on code clarity and personal discretion.

In essence...

It boils down to your personal choice


Code Snippet:

$(() => {
  var with_default_profile = $(".s-lib-featured-profile-image")
  .filter(function() {
    return $(this).find("img").attr("src") === "//libapps.s3.amazonaws.com/apps/common/images/profile.jpg";
  })
  with_default_profile.hide();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="s-lib-featured-profile-container"><a href="/prf.php?account_id=127256">
    <div class="s-lib-featured-profile-image">
      <img src="//libapps.s3.amazonaws.com/apps/common/images/profile.jpg" alt="Julie Brewer's picture">
    </div>
    <div class="s-lib-profile-div s-lib-featured-profile-name">Julie Brewer</div></a>
</div>
 
 
 
<div class="s-lib-featured-profile-container"><a href="/prf.php?account_id=131922">
    <div class="s-lib-featured-profile-image">
      <img src="//libapps.s3.amazonaws.com/accounts/131922/profiles/125264/Caldwell_John.jpg" alt="John Caldwell's picture">
    </div>
    <div class="s-lib-profile-div s-lib-featured-profile-name">John Caldwell</div></a>
</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

Is there a way to adjust the font size of a vue-good-table within a vue.js project?

I am facing an issue in Vue.js where the content of a page gets "cut off" on the right side when trying to print it. I'm wondering if I should use a function to solve this problem? <vue-good-table :columns="columns" :rows="rows" ...

How can I improve a gif's background for optimal viewing on mobile devices?

Hey there! I'm facing an issue with a gif running as the background on my website. On my phone, the whole screen isn't filled up and there's just a black space halfway down. You can check it out at . Do you know how to make the gif take up t ...

Encountering issues when using array.map with null entries in a react application

Struggling to iterate over the location array and map it? Despite several attempts, handling the null object within the array seems challenging. What am I missing here? While using a for loop resolves the issue, the map function is proving to be a roadbloc ...

Expanding box geometry from a single side in Three.js

Just starting out with three.js and my first task was to create a box geometry that could be increased from only one side. Issue : When increasing the width or height of an object, both sides automatically expand. Check out this jsFiddle Example I waste ...

Error encountered in thread "main": Issue with parsing string literal

import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class FindElementsUsingJS { static WebDriver driver= new FirefoxDriver(); public static void main(Stri ...

Steps to bring an image forward on a canvas to enable its onclick function

One of the challenges I'm facing involves an image of a pawn on a board. The image is set up with an onclick function that should trigger an alert when clicked. However, there is a canvas positioned above the image, which is interfering with the funct ...

Access nested objects in Javascript (Vue)

Struggling with a simple question as a beginner... I am dealing with an object of objects: monsters { place1: { monster1: { ... } monster2: { ... } } place2: { monster3: { ... } monster4: { ... } } } I ...

Utilize JSON parsing with AngularJS

My current code processes json-formatted text within the javascript code, but I would like to read it from a json file instead. How can I modify my code to achieve this? Specifically, how can I assign the parsed data to the variable $scope.Items? app.co ...

Error in Virtual Earth: The function is undefined

Currently, I am attempting to implement lazy loading for a Virtual Earth map within a JQuery UI tab. Concurrently, there is also a Google map in another tab. My goal is to synchronize the center locations of both maps whenever a user interacts with either ...

Updating or swapping images using JavaScript and HTML

I am looking to implement a feature similar to Twitter, where uploading a picture automatically updates the avatar by displaying a spinner while the new image loads. I attempted to accomplish this with the following code: <script language="javascript"& ...

Using Vue Axios to load a Laravel view can be a seamless process that

I'm attempting to create a hyperlink to a Laravel view named faq.blade.php from my Vue component. I've tried using axios, and even though it logs the response in the console, the view isn't loading. How can I resolve this issue? FaqControll ...

How to add a line break within the :after pseudo-element using CSS

I've been struggling to split text inside an :after pseudo-element of a label that receives its content from a data- attribute. I've attempted using word-break, as well as playing around with width, max-width, and position:relative, but nothing s ...

The alternative text for the oversized image exceeds the boundaries

After setting the width and height for an image, along with testing overflow:hidden, I've encountered an issue where the alt text for a broken image overflows the bounds of the image and the image size is lost. How can I contain the alt text within th ...

dynamic dropdown displaying colors for selection

Using a bootstrap form to add a printer involves selecting the material and color. The dynamic dropdowns are functioning correctly, but it is necessary to display the selected color for user clarity. Please guide me on how to pass the color along with its ...

What is the best way to monitor changes in objects within a JavaScript array?

Currently, I am in the process of developing a Todo application using electron and Vue.js. In my project, there is an array of objects called items. Each object follows this format: {id: <Number>, item: <String>, complete: <Boolean>, ...

When the collapse button is clicked, I aim to increase the top value by 100. Subsequently, upon a second click, the top value should

https://i.stack.imgur.com/p9owU.jpghttps://i.stack.imgur.com/Kwtnh.jpg I attempted to utilize jQuery toggle, but unfortunately, it is not functioning as expected. <script> $(document).ready(function () { $(".sidebar ul li&quo ...

What is the best way to separate a string using a comma as a delimiter and transform it into a string that resembles an array with individual string elements

I am in search of a way to transform a string, such as: "one, two, three, four" into a string like: "["one", "two", "three", "four"]" I have been attempting to devise a solution that addresses most scenarios, but so far, I have not been successful. The ap ...

I'm struggling to figure out the solution for this error message: "Unhandled Rejection (Type Error): Cannot read property 'filter' of undefined." Can someone please assist me with resolving this

Can you assist me? I am a beginner when it comes to javascript/React. I am currently following this tutorial https://github.com/Azure-Samples/js-e2e-client-cognitive-services and encountering the following error message: "Unhandled Rejection (TypeErro ...

Angular first renders a component before removing another one using ng-If

I have two components that are displayed one at a time using an ngif directive. <app-root> <first-Comp *ngIf="showFirst"></first-Comp> <second-Comp *ngIf="!showFirst"></second-Comp> </app-root> Here are some key ...

Attempting to devise a jQuery algorithm sorting method

To enhance the answer provided in this post: How to stack divs without spaces and maintain order on smaller screens using Bootstrap I've been exploring ways to develop a jQuery script that dynamically adjusts the margin-top of div elements based on t ...