How to use JavaScript to identify the CSS property value of an HTML element

Everything seems fine until the alert pops up, but the 'if' statement is not executing properly. Here is the program stack. Is there a way to check the display property of a div to see if it's set to "block" or "none"?

for(i=1;i<=10;i++)
  {
   alert("Hamdun Soft Past Job Will be Deleted");
   if(document.getElementById(i).style.display=="block")
   document.getElementById(i).innerHTML="Hamdun Soft Is Clear Now";           
 }

Oh! Remember that out of the divs with IDs ranging from 1 to 10, one has its display set to "block" while the rest are set to "none". I set this using another JavaScript program. But now, I need to identify which one is set to "block". Thanks.

Answer №1

To resolve the issue, you must utilize the computed style and not just rely on inline styles like Element.style.display.

for(i=1;i<=10;i++){
    var elem = document.getElementById(i);

    if((elem.currentStyle ? elem.currentStyle.display : getComputedStyle(elem, null).display) == 'block')
    elem.innerHTML="Hamdun Soft Is Clear Now"; 
}
<div id="1">aaa</div>
<div id="2">aaa</div>
<div id="3">aaa</div>
<div id="4">aaa</div>
<div id="5">aaa</div>
<div id="6">aaa</div>
<div id="7">aaa</div>
<div id="8">aaa</div>
<div id="9">aaa</div>
<div id="10">aaa</div>

Note: It is important to first check elem.currentStyle for compatibility with older versions of IE.

Answer №2

Zigmantas pointed out that the issue lies with the id in this case. In HTML4, an id must begin with a letter, although numeric IDs are now permitted in HTML5, it can still create other complications.

It's important to note that the style needs to be explicitly defined for the element. In this instance, the third div has the style set but not inline, so it doesn't get selected. The first div does have inline styling as you requested.

<html>
<head>
<style type="text/css">
div:last-child <!-- #3 does not work in chrome -->
{
  display:block;   color:red
}
</style>
</head>
<body>
<section>
<div id="1" style="display:block;color:red">one</div>
<div id="2" >two</div>
<div id="3" >three</div>
</section>
</body>

<script>
for(i=1;i<=3;i++)
  {
   alert("Hamdun Soft Past Job Will be Deleted");
   // Using getComputedStyle and starting IDs with letters would be better practices.
   if(document.getElementById(''+i).style.display=="block")
   document.getElementById(''+i).innerHTML="Hamdun Soft Is Clear Now";           
 }
 </script>
</html>

Answer №3

Make sure to use

document.getElementById(i).style.display==""
instead, as the "display" property defaults to an empty string when not specified initially.

function Display()
{
for(i=1;i<=6;i++)
  {
   if(document.getElementById(i).style.display=="block" ||     document.getElementById(i).style.display=="")
   document.getElementById(i).innerHTML="Hamdun Soft Is Clear Now";           
 }
}
<div id="1" style="display:none;">111</div>
<div id="2" style="display:block;">222</div>
<div id="3">333</div>
<div id="4" style="display:inline;">444</div>
<div id="5" style="display:list-item;">555</div>
<div id="6" style="display:initial;">666</div>

<input type="button" onclick="Display()" value="Press">

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

Locating elements with Selenium Webdriver using xpath

<a style="color:White;" href="javascript:__doPostBack('dnn$ctr674$Case$gvCaseSearchDetails','Page$777')">777</a> Can anyone help with writing an xpath for the HTML code above? The goal is to locate elements using the identi ...

Upon refreshing the page in Javascript, the element mysteriously vanishes without a trace

After implementing a function that should display "barProgress25" and hide "barProgress0" when a button is clicked, I encountered an issue. Upon clicking the button, the function works as intended but upon page refresh, "barProgres ...

There seems to be a lack of information appearing on the table

I decided to challenge myself by creating a simple test project to dive into Angular concepts such as CRUD functions, utilizing ngFor, and understanding HttpClient methods (specifically get and post). After creating a Firebase database with an API key and ...

What is the code to incorporate a color using PHP?

Question: Is there a way to indicate approval with green color and decline with red color? I've searched for a solution but couldn't find one. PHP Code: <?php if(isset($_POST['approve'])) { $msg = "Approved"; ...

Is there a way to adjust the orientation of a <video> element without affecting the orientation of the video controls?

<video controls> </video> video { transform: scaleX(-1) } This CSS code flips the video horizontally, but it also flips the control buttons along with it. I attempted to flip the wrapper element containing the video using .wrapper {transfor ...

Why does the old component of the router still receive and handle events when <router-view/> changes?

Ugh... I need to explain a tricky situation I'm facing. I have a parent component that has two children listening for the same event and performing similar actions (see code snippet below): mounted() { EventBus.$on('edit', (data) => { ...

Color the area entirely in black

I am currently working on a project for one of my courses, where I have created a website for a specific service. However, I am facing some challenges and things are not going as smoothly as I had hoped. Here is a screenshot of the page: https://i.stack.im ...

ASP TextChanged event is not triggering unless the user presses the Enter key or tabs out

My code is functioning correctly, however, the TextChanged event is triggered when I press enter or tab, causing my code to execute. I would like to be able to search for a record without having to press enter or tab. ASP: asp:TextBox ID="txtNameSearch ...

Reorganize the layout of elements based on the array of element IDs

I have a task to complete that involves two 'ul' elements with unique id's and 'li' elements within them. <div id="sr"> <ul id="li-fav"> <li id="app-1">a</li> <li id=" ...

Is it possible for me to use @import to selectively choose what I need and disregard the rest?

If I am utilizing SASS and wish to incorporate a significant portion of another existing stylesheet, whether it is in SASS or CSS format, I have the option to import that particular sheet using @import, then employ @extend to apply some of its rules. Is ...

Guide to displaying a quick message and then redirecting the page upon clicking a button in ASP.NET

Hello, I am encountering an issue with a submit button on my page. I want the user to be prompted with a message saying "Are you sure to submit that page really" when the submit button is clicked, and if they click yes, then it should redirect to another p ...

Skewed top-left border surrounds the element with a dashed design

I'm looking to achieve a border effect similar to the one shown in the image linked below: https://i.sstatic.net/a4hCQ.jpg Here is the code I have tried so far: <p>Some Text</p> p{ -webkit-transform: perspective(158px) rotateX(338deg ...

The component fails to display during my testing efforts

I am encountering a peculiar issue. In my setup, I am using jasmine 2.0, react 0.13.3, react-router 0.13.3, and various other packages. The problem lies within my test suite where it fails to findRenderedDOMComponentWithTag(). Let me provide a specific exa ...

What is the proper way to bind CoreUI's CSwitch component?

I am trying to incorporate the CSwitch component into a DevExtreme data grid. While the DxSwitch component functions correctly, I am unable to get the CSwitch to work properly. It seems like I might be using the wrong binding. Could that be the issue? < ...

Custom date formatting with jQuery table sorting

I have been using a jQuery plugin called Tablesorter to sort a table. I am facing an issue with sorting dates in the yyyy MMM dd format, especially because my date inputs are in French. Here is an example of how the dates are formatted: 2014 janv. 05 20 ...

Convert Binary Data to PDF Using Javascript Through Streaming

Upon requesting a Web-service, I received the following response (PDF file Streamed) %PDF-1.5 %µµµµ 1 0 obj <</Type/Catalog/Pages 2 0 R/Lang(en-GB) /StructTreeRoot 10 0 R/MarkInfo<</Marked true>>>> endobj 2 0 obj <</Type/ ...

What is the best way to align two items where one is centered and the other is positioned to the left?

In an attempt to customize a chat call to action, I am looking to have an icon aligned to the left and some centered text. Here is an example of how I envision it: [ @ Text aligned in center ] Here is what I have tried so far: .icon{ justify-self: ...

Update the state within a callback to display corresponding content in a React component

Struggling with rendering conditional content based on the presence of a value. In my component, if an API key is not provided, I want to display an input field with a button. Once the API key is stored using `electron-json-storage` and set as a state, the ...

Problem encountered with AngularJS html5mode URL functionality

I am encountering an issue with my AngularJS application that does not contain any nodeJS code. The problem lies in removing the # from the URL and I have implemented ui-routes for routing. 'use strict'; var app = angular.module('myapp&apos ...

Managing time in an Angular application using Typescript

I am facing an issue with formatting the time obtained from an API in my FormArray. The time is received in the format: 14.21.00 My goal is to convert this time to the following format: 2:21 PM I have attempted to format it using Angular's DatePip ...