Apply a specific class to the div elements that have an image with a designated width

Hello, let's dive into the code.

<div class="nyhet"> <img src="#" width="785" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="390" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="785" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="390" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="785" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="390" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="785" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="390" class="attachement-full" /></div>

Alright, so here's what I'm aiming for - adding a class of "large" to divs with images that have a width of 785 and a class of "small" to divs with images that have a width of 390.

This is the desired outcome:

<div class="nyhet large"> <img src="#" width="785" class="attachement-full" /></div>
<div class="nyhet small"> <img src="#" width="390" class="attachement-full" /></div>
<div class="nyhet large"> <img src="#" width="785" class="attachement-full" /></div>

and so forth. This is my attempt so far.

$(document).ready(function(){
  var x = $(".nyhet").length;
  for (var i=0; i<x;i++){
    n = $(".attachement-full:eq(i)").attr("width");
    if (n<785) {
      $(".nyhet:eq(i)").addClass("small");
    } else {
      $(".nyhet:eq(i)").addClass("large");
    }
  }
});

I opted for using .attr instead of .width due to potential image loading delays when the script runs.

Your assistance on this matter would be greatly appreciated!

Answer №1

Your code snippet didn't specify whether images with a width of 786 should be considered large or not, so here's a solution for handling different image sizes:

$(".nyhet img").each(function() {
    var $parent = $(this).parent(".nyhet");
    if(this.offsetWidth >= 785) {
        $parent.addClass("large");
    } else {
        $parent.addClass("small");
    }
})

Answer №2

There is a simpler solution using only one selector:

$("img[width=785]").parent(".news-item").addClass("wide");
$("img[width=390]").parent(".news-item").addClass("narrow");

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

What is the process for sending an HTTP request within the Dialogflow -> Fulfillment environment?

When it comes to interacting with the API of my website to rectify the response for Google Assistant, I am facing some difficulties. 'use strict'; var requestNode = require('request'); const functions = require('firebase-function ...

Unable to eliminate top margin in Bootstrap 3 affix feature

Struggling to locate the source of the margin-top when utilizing the affix plugin on my Navbar. You can view [my website here] for better understanding. Should I be implementing Javascript to solve this issue? My current skills in that area are not very ...

Transforming website content into HTML code

I am in need of a solution to convert a webpage into an HTML page programmatically. I have researched several websites, but the information provided only covers converting pages into PDF formats. Currently, my program involves saving a page as .html and th ...

The transformation does not occur again when the window is resized

After seeing a question on How to make svg RTL I attempted to make my svg RTL using: transform: translate(100%, 0) scale(-1, 1); However, I noticed that when resizing my browser window, the transform is not properly applied and the line origin shifts ...

Updating a DIV in JQuery with a new URL submitted through a form

I am working on a form that includes a text box within a div tag. My goal is to dynamically change the contents of this div based on the user input in the textbox using a PHP GET request. For example, if the user types "hell" into the textbox, I want the ...

Why is the image auto-swapping script failing to display images frequently?

I have a script that is currently running to rotate between two different logos on my webpage. What I am attempting to achieve is for the page to load and then seamlessly transition from one image to the other without any blank space. Below is the code I ...

ASP.net and jQuery failing to submit form through email to resolve the issue

I'm currently grappling with a challenge and could use some assistance. Essentially, I have an HTML form styled as a wizard, utilizing the jQuery form wizard plugin along with plugins like jQuery.Form, jQuery.Validation, and jQuery.History. My intent ...

Exporting the default object scope in Vue.js allows for easy sharing

Could someone please clarify the usage of export default in Vue files? Appreciate it. For example: HelloWorld.vue <template> <div id="app"> <HelloWorld /> </div> </template> <script> import HelloWor ...

Add a delay in jQuery so that when triggered by a click, the element fades out smoothly or instantaneously

Currently, I am working on creating a script for a notification popup. My goal is to have the popup fade out either after a certain number of seconds or when the user clicks on the message. While I have been successful in getting each effect to work indi ...

Displaying multiple div elements when a button is clickedLet multiple divs be

ISSUE Hello there! I'm facing a challenge where I need to display a div when a button is clicked. The issue arises from having multiple divs with the same class, making it difficult for me to target each individual div... Image1 Image2 Desired Outco ...

Steps to include a fresh string into an array within a json document

I'm currently working on a Discord bot that uses a profile.json file. My goal is to have a specific command that allows users to add input arguments to an array within the file, like this: {"Profile_name":"id":"idhere", "array":["item_1"]} The ultim ...

Is it possible to increment an integer value in jQuery after obtaining the sum result?

Actually, I'm trying to extract the integer value from my input field. For example, if I enter the value 4+5, I want to display the result as 9 in a separate div. However, instead of getting the expected result, I am receiving [object Object]. I&apo ...

SyntaxError: End of input caught unexpectedly (NodeJS TCP server)

My simple tcp server has the capability to send and receive json data. Here is a snippet of my code: // Handling incoming messages from clients. socket.on('data', function (data) { var obj = JSON.parse(data); if(obj.type == "regis ...

The expected outcome of the value display in CSS is not being achieved as anticipated

Here is some HTML code: <!DOCTYPE html> <html> <head> <title>Testing Page</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <h1 class="hid ...

Create an Angular directive that dynamically adds a template to a textbox when the Spacebar or enter key

Using AngularJS, I aim to display an HTML table in a textbox when the spacebar is pressed, and add the table element to the textbox. To achieve this, I have created a directive, but I am unsure if I have followed the correct approach. Let me provide a deta ...

implementing ajax form submission in codeigniter

After submitting my form, validation is checked in the JavaScript file, and then the kickerLogin() function is called. I receive an alert message of datastring. However, the data is not sent to the specified URL in the AJAX request, but the form still ge ...

Two pictures, one adjusting in size and one staying the same size

I am working on a design with an 800px wide div that contains side-by-side images - one photo and one map. The challenge I am facing is that the map, which is 300px in width and has intricate details, becomes unusable when resized for smaller screens. I wa ...

Lower the placement of Glyphicons

I have recently implemented a custom font on my website. Unfortunately, this font is not standard and its alignment is off. As a result, when I use this font with Twitter Bootstrap glyphicon, they do not appear in the same line. Is there a way to adjust t ...

Diverse Values within the Inner Border

Is it possible to create an inner border with unique values for each side? For instance: Top: 20px Right: 80px Bottom: 40px Left: 10px Can you provide an example of how this can be achieved? Thank you! :) ...

Sharing information using Fancybox 2

I have encountered an issue while using a form within a fancybox window to post data via Ajax to a php page. The form works perfectly fine when run outside of the Fancybox - insertion and response are both successful. However, when I run the same page thr ...