``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

What strategies can be used to ensure that the page layout adjusts seamlessly to even the smallest shifts in window size?

Of course, I am familiar with media queries and how they allow us to set specific min-width and max-width ranges for CSS changes. However, when I look at the website styledotme.com, I notice that the block/div beneath the navigation bar gradually shrinks ...

What's causing this sluggish performance?

I'm in the process of developing a Google Chrome extension and I can't help but wonder why window.onload = loadPage; function loadPage() { document.getElementById('nav-robux-amount').innerHTML = '0'; console.log(" ...

How to create a non-clickable section within a linked div

Website: I am interested in linking just the triangle banner located at the top right corner of the page. The triangle image is actually a transparent rectangle with only the triangle portion filled in, so I want to ensure that only that particular sectio ...

Rearrange the order of divs dynamically to prevent wrapping/overflow, no need for media queries

Can someone help me with this issue? I am trying to create a navigation bar with centered menus/links, a logo on the left, and call-to-action buttons and icons on the right. If the content overflows or wraps, I want the center column to move to the next l ...

Guide on clicking an element within a hidden iframe using Python Selenium

I am facing a challenge in finding elements within an iframe tag. Surprisingly, the HTML source does not contain any iframe tags. However, upon inspecting the element, I can see that there is indeed an iframe tag present. How can I tackle this issue using ...

PHP - Offline/Online Status Polling Protocol Guide for Beginners

I am in search of a solution to track the online and offline status of users on my website. My site is a single page with no clickable links, so users may leave their tabs open for long periods without interaction. It is not essential to pinpoint the exact ...

Retrieving posts by their ID leads to consistently fetching the most recent post in WordPress

My goal is to fetch a specific post based on its ID. Within my custom post type Stories, there are currently three posts available: Blog 1 (ID: 1) Blog 2 (ID: 14) Blog 3 (ID: 49) I have defined a variable called $story_one with the value of 14. Now, my ...

What is the most efficient method for incorporating fonts.googleapis.com into CSS files for use on both HTTP and HTTPS pages?

My website functions correctly when accessed through URLs that start with either http:// or default to the http protocol if not specified. However, an error occurs stating that the main.css file cannot be found when the URL begins with https://. The lates ...

Arranging an array of arrays based on the mm/dd/yyyy date field

Currently, I am facing an issue while attempting to sort data obtained from an API by date in the client-side view. Here is an example of the data being received: address: "1212 Test Ave" address2: "" checkNumber : "" city: "La Grange" country: "" email: ...

Where should the defer.resolve be placed when executing a function asynchronously in a loop using JavaScript?

As someone coming from a java/python background, I am venturing into the world of JavaScript. My current task involves creating a product list with detailed descriptions of its children included in a JSON array. Here is an example of what I want to achiev ...

Creating a unique, random output while maintaining a log of previous results

While working on a recent project, I found myself in need of a custom Javascript function that could generate random numbers within a specified range without any repetitions until all possibilities were exhausted. Since such a function didn't already ...

The error message 'Cannot read property 'navigate' of undefined' is displayed because the function '_this.props.navigation.navigate' is not

I'm facing an issue trying to access 'Home' from Form.js. Despite my efforts in arrowF, routes, and other methods, the same error persists. How can I resolve this? In my Form.js file, when I call onPress=(), I have tried using functions, ...

What is the best way to transfer data from an HBS template (HTML) to an Axios POST request?

Just diving into nodejs and express! I want to pass the user input (an email) to axios.post request's data when the "submit" button is clicked. I've verified that hard-coded data in the axios request is functioning correctly. data_email.hbs &l ...

Jquery(Ajax) call encountered a problem when attempting to send the object

Struggling to send data to a MongoLab DB using JS and JQueryAjax call. The issue lies in being able to see the OID in the DB but no data is actually populated. Upon checking the code and network settings, it's evident that the payload always remains e ...

Sending Information within Controllers with AngularJS

I have a unique scenario in my application where I need to pass input from one view to another. I have set up a service as shown below: .service('greeting', function Greeting() { var greeting = this; greeting.message = 'Default&ap ...

What are the steps for implementing Babel in a CLI program?

Currently, I am working on developing a CLI program in Node using Babel. While researching, I came across a question on Stack Overflow where user loganfsmyth recommended: Ideally you'd precompile before distributing your package. Following this ad ...

What is the method of generating an HTML tag solely using CSS?

Looking to style HTML tags without altering them in any way? Consider this example: <div id="Code_G" class="editor-group"> editor-group<br /> <div id="Code_L" class="editor-label "> editor-label </div> < ...

Is it necessary to validate input for a login form? Some may argue that it creates unnecessary overhead and introduces concerns about an excess of javascript

While working on input validation for my registration form, the idea of implementing it on my login form also crossed my mind. My login form only requires an email and password. I'm considering validating whether the email entered is a valid email add ...

Having Trouble Choosing Options From Dropdown Menu Using Index in Selenium with Java

I am familiar with how to choose an element from a dropdown using the selectByIndex method. However, when attempting to use selectByIndex (select.selectByIndex(index)) on the HTML snippet below: <select id="destinationAllocationId" name="destinationAll ...

Tips for parsing JSON using JavaScript

I am looking to iterate through a JSON object that looks like {"key1":"val1","key2":"val2","key3":"val3"} in a loop. Here is my attempt: var inobj = '[{"key1":"val1","key2":"val2","key3":"val3"}]'; var obj = eval(inobj); for (var i = 0; i ...