``Is it possible to adjust the style of an HTML element based on the style of another element?

Within my web application, I am dynamically changing the style of an HTML element using JavaScript.

Below is the code snippet:

function layout() {
    if(document.getElementById('sh1').getAttribute('src') == "abc.png") {
        document.getElementById("sh1").style.display="none";
    } else {
        document.getElementById("sh1").style.display="block";
    }
}

The corresponding HTML code is:

<img id="sh1" src="abc.png" />

Now, I want to ensure that if the style of the image element is set to display:none, then the following elements:

<p id="Text1">Name<br />description</p>

also have their style changed to display:none. Similarly, if the image element's style is set to display:block, then the above elements' style should also be updated to display:block automatically.

How can this be achieved?

Answer №1

Make sure to include the other element in your function as well. Here is an example of how you can do that:

function updateLayout(){
    if(document.getElementById('sh1').getAttribute('src') == "abc.png"){
        document.getElementById("sh1").style.display="none";
        document.getElementById("Text1").style.display="none";
    } else {
        document.getElementById("sh1").style.display="block";
        document.getElementById("Text1").style.display="Block";
    }
}

If you prefer, you can also consider putting both elements in a container and performing operations on the entire container instead =)

Answer №2

Assuming I've interpreted your message correctly, it seems like you're looking for...

function layout(){
  if(document.getElementById('sh1').getAttribute('src') == "abc.png"){
    document.getElementById("sh1").style.display="none";
    document.getElementById("Text1").style.display = "none"; //Hiding the description
  } else {
    document.getElementById("sh1").style.display="block";
    document.getElementById("Text1").style.display="block"; //Showing the description
  }
}

If this function is specific to this particular image and description, then it should work well. However, if you are applying this logic to multiple images, there may be a more efficient way to accomplish this with a generic function.

Answer №3

To combine your image and text, my suggestion would be to utilize jQuery to modify the markup. You can wrap the image and text together using this method. For a demonstration, you can refer to the provided link for a working example.

<figure id="sh1" class="picture active">
   <img src="http://placehold.it/100x100&text=abc.png" />
    <figcaption><span class="name">ABC</span><span class="desc">This is a description</span>
    </figcaption>
</figure>

<figure id="sh2" class="picture">
   <img src="http://placehold.it/100x100&text=xyz.png" />
    <figcaption><span class="name">XYZ</span><span class="desc">This is a description</span>
    </figcaption>
</figure>

http://jsfiddle.net/Qvb4U/1/

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

Struggling to reveal concealed items on a webpage using jQuery and attempting to cycle through an array without success

Looking to display or hide certain sections on a page based on specific conditions. I want to only show the sections of the page that contain words from the conditionsToShow array. function hideWorkflowConditions() { // initially hide the elements ...

Save a PNG file using the HTML5 Canvas when the Submit button is clicked, with the help of PHP

I am looking for assistance with a signature capture form. I came across a standard template on Github that works perfectly, but I wanted to customize it further. However, my Javascript skills are still in the early stages. The current code allows you to c ...

Using NPM packages with vanilla JavaScript can be achieved without the need for an HTML file

Is there a way to include an NPM package in my index.js file without installing it via a package manager? I do not have an HTML file, only the index.js file which is executed with 'node index.js' command. Since I cannot use a CDN, is there any me ...

CSS: Creating a block that stretches the entire width of its parent block

I've been facing the same issue multiple times. Whenever I use the float property to display one block, the next block ends up overlapping with the first one. For example: Consider the following block of code: .row_item{ width: 30%; display: block; ...

Guidance on redirecting and displaying the URL retrieved from an API response object in the browser using express and axios

Currently in the process of developing a payment gateway using the Paystack API along with Axios for managing HTTP requests. After thoroughly examining their API documentation and reviewing their Postman collection, I was able to grasp how to structure th ...

Issues with rendering of triangles in WebGL

My current project involves creating a webGL application for rendering randomly generated terrains. While the terrain rendering works smoothly, I've encountered an issue with rendering a simple quad to represent water - the triangles of the water are ...

A configuration for ".node" files is missing: specifically, the loader for node_modules/fsevents/fsevents.node in a project using Vite

Everything was running smoothly in my Vite + React project until last week when out of nowhere, I encountered this error: No loader is configured for ".node" files: node_modules/fsevents/fsevents.node node_modules/fsevents/fsevents.js:13:23: 1 ...

What is the best way to add JSON data to a table?

I have developed a php script to create json data. However, I am facing an issue while trying to display this generated json data in a table. While my php code successfully generates the data, it is unable to insert it into the table. I would appreciate an ...

Having trouble getting Bootstrap's Javascript to function properly in a Rails 6 webpacker configuration?

Recently initiated a brand new Rails 6.0.3 project and integrated jQuery and Bootstrap into it. Surprisingly, jQuery is functioning smoothly, and the Bootstrap CSS appears to be rendering correctly. However, every attempt to execute $.fn.tooltip.Construc ...

"Let's delve into the world of dynamic variables and Javascript once

As a newcomer to JS, I've scoured countless posts for solutions, but nothing seems to work for me. The issue arises when trying to abstract the code to handle all variables rather than just explicitly expressed values. I am open to alternative method ...

Ensure that every HTML link consistently triggers the Complete Action With prompt on Android devices

After extensive searching, I have yet to find a solution to my issue. I have been developing a web application that allows users to play video files, primarily in the mp4 format. Depending on the mobile browser being used, when clicking the link, the vide ...

A full-width CSS menu featuring dropdowns beneath each entry for easy navigation

Check out the JSFiddle here I've created a full-width CSS menu that spans the entire screen, but I'm struggling to figure out how to make the corresponding subnav items appear below their parent items. Is it even possible to achieve this design ...

Creating a responsive design for a centered image with absolute positioning

I'm trying to align an image at the bottom of a div while also centering it using the following CSS: HTML: <div class="myDiv"> <img src="http://bit.ly/1gHcL8T" class="imageCenter" /> </div> CSS: .myDiv { width: 80%; height: ...

Deletion of component with setTimeout in React Class Component

I have a notification feature that disappears after a certain delay when rendered. The issue arises when attempting to cancel this automatic removal using clearTimeout, as it doesn't seem to work. See below class Notify extends React.Component { ...

Implementing a 'Load More' button for a list in Vue.js

I am currently working on adding a load more button to my code. While I could achieve this using JavaScript, I am facing difficulties implementing it in Vue.js. Here is the Vue code I have been working with. I attempted to target the element with the compa ...

The use of '-' in v-bind:style within Vue.js

I'm having trouble figuring out how to use CSS code with dashes in v-bind:style. When I attempt something like this: <DIV style="width:100px;height: 100px;background-color: red;cursor: pointer;" v-bind:style="{ margin-left: margin + 'px' ...

Encountering a Circular JSON stringify error on Nest.js without a useful stack trace

My application is being plagued by this critical error in production: /usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:137 ? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(message, (key, value ...

My applications are not firing the deviceready event as expected

Struggling to incorporate a cordova plugin into my vue.js project using vue-cordova. Specifically, I am attempting to utilize the open-native-settings plugin to access device settings on iOS or Android. While it works seamlessly in the demo app provided b ...

Angular Fire: The $on method is missing and causing an error stating that undefined is not a function

I am currently attempting to log my Firebase data to the console, but I keep encountering an error stating undefined is not a function. Below is the full error message: TypeError: undefined is not a function at Object.childAdded (http://localhost:9000/scr ...

Performing a JavaScript/jQuery callback to server without the need for an accompanying executable backend

Today, a colleague in the tech world posed an interesting question to me: Can jQuery (or JavaScript in general) retrieve information about the filesystem from its source without the need for executable code? Initially, I instinctively responded by saying t ...