Transitioning the style code from inline to the head of the document disrupts the straightforward JavaScript intended to

As I delve into the world of web development, I encountered a simple issue that has been causing me frustration for the past hour. It involves code to display the border color of a div element using an alert. The code works perfectly fine when the style is applied inline, but as soon as I move it to a style element in the head section, it stops working.

Here's the working code:

function myFunction() {
  alert(document.getElementById("myDiv").style.borderColor);
}
<div id="myDiv" style="border:thick solid green">This is a div.</div>
<br>
<button type="button" onclick="myFunction()">Return border color</button>

And now, the non-working code:

function myFunction() {
  alert(document.getElementById("myDiv").style.borderColor);
}
<style>
  #myDiv {
    border: thick solid green;
  }
</style>
<div id="myDiv">This is a div.</div>
<br>
<button type="button" onclick="myFunction()">Return border color</button>

I simply moved the style attribute from the div tag to the head section. Can anyone explain why this change caused it to stop working and guide me on how to fix it?

Answer №1

The style attribute will only apply inline styles to your elements. If you need to access the actual computed style, you can utilize the getComputedStyle function in modern browsers or the currentStyle property in older versions of Internet Explorer:

function retrieveBorderStyle() {
  var element = document.getElementById("myElement");
  var computedStyle = window.getComputedStyle ? getComputedStyle(element) : element.currentStyle;
  alert(computedStyle.borderColor);
}
<style>
  #myElement {
    border: thick solid blue;
  }
</style>
<div id="myElement">This is a sample element.</div>
<br>
<button type="button" onclick="retrieveBorderStyle()">Get border color</button>

Answer №2

When accessing the element.style property, you are retrieving the style attribute of that particular element. In case the attribute is removed, as illustrated in the second example, it will no longer function properly.

To obtain the actual styles that have been applied to an element, you must utilize the Window.getComputedStyle() method. An illustrative example of its usage is:

var targetElement = document.getElementById("specificDiv");
var computedStyles = window.getComputedStyle(targetElement);
alert(computedStyles.color);

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

next.js experiencing hydration issue due to using div tag instead of main tag

I've come across an issue with hydration in NextJS and after debugging, I discovered that using the div tag instead of the main tag is causing this problem. The error message I'm receiving Here is the code snippet that triggered the error impo ...

How can we initiate an AJAX request in React when a button is clicked?

I'm fairly new to React and I'm experimenting with making an AJAX call triggered by a specific button click. This is how I am currently using the XMLHttpRequest method: getAssessment() { const data = this.data //some request data here co ...

Switching icon images using JQuery based on state changes

I'm attempting to switch the background image of my webpage's "body" element when the user toggles between playing and pausing music icons. This is what the CSS for the "body" element looks like: body { background: url('https://s3-us-wes ...

Issue with Textarea not updating when props change in a React component

I am facing an issue with updating the default value of a textarea based on props passed from a parent component. Strangely, the update works when using 'value' but not when using 'defaultValue'. However, I need the textarea to be edita ...

Splitting the page in half

Is there a way to ensure that the LeftArea and wuiMainPageNav sections stay side by side regardless of the browser window size? When I resize the window, the layout gets messed up with wuiMainPageNav moving down. Any suggestions on how to address this issu ...

Guide to successfully redirecting to a new page post login, along with sending a token as a handler to middleware using the express framework

My application utilizes nextJS, express JS, and JWT. I have created two pages - a login page and an admin page where the latter is protected and only accessible after verifying the token using JWT. My goal is to redirect users to the admin page immediately ...

Widget Issue: Problem with Setting jQuery Datepicker Format to European Style

I could really use some assistance with this issue. My goal is to display the check-in and check-out dates in European format (dd/mm/yy) within the input field on this specific page: (username: 'numberone' ; pass: 'num270514'). When t ...

Styling jQuery Draggable and Droppable <li> elements

I am facing a challenge with my drag and drop functionality using jQuery. While the drag drop feature works perfectly, I need to display two separate pieces of information from a database on each "li" item in different styles. My goal is to include a "tra ...

Having trouble changing a state from a class component to a function component in React

I've been updating my React projects by converting all my classes to functions. However, I encountered an issue where ESLint is reporting a parsing error in my code. Oddly enough, if I remove just one line, the error disappears. Here's the snippe ...

Every time I attempt to send a post request, I receive back only the creation date and the unique objectID

Whenever I send a post request, only the created date and objectID are returned. Whenever I send a post request, only the created date and objectID are returned. This issue persists even after multiple attempts. I attempted to verify it using Postman ...

Understanding ReactJS's process of batching all DOM updates within a single event loop, ultimately minimizing the number of repaints needed

While perusing an article on DOM updates in ReactJS, I came across the concept of React updating all changes within a single event loop. Having a background in understanding event loops in JavaScript and how they function in core JavaScript, I am curious ...

Using inline JavaScript to style an element when clicked

Looking for assistance with styling a link. I've connected an external stylesheet to my HTML file, so that part is all set. The goal is to modify the text-decoration when the onclick event occurs. Here's what I currently have: <a class="dopel ...

"Enhance your listening experience with an audio player featuring album covers as captivating

Is there a way to create an audio player with the album cover image serving as the background, while ensuring all control buttons are displayed on top of that same image? I attempted using the following code snippet: <audio controls = 'controls&ap ...

While v-carousel adjusts to different screen sizes, the images it displays do not adapt to

Whenever I implement v-carousel, everything seems to be working well, but there is an issue on mobile. Despite the carousel itself being responsive, the images inside do not resize properly, resulting in only the center portion of each image being displaye ...

Transforming jQuery into vanilla JavaScript in order to create a customized dropdown select functionality

I am struggling with converting jQuery code to pure JavaScript for a custom select element. https://codepen.io/PeterGeller/pen/wksIF After referencing the CodePen example, I attempted to implement it with 3 select elements. const select = document.get ...

How well do social media share buttons perform on websites

I'm experiencing issues with the performance of my gallery ever since I added social buttons. Currently, there are around 30 thumbnails in the gallery, each accompanied by four social buttons for different services like Facebook, Google Plus, Twitter ...

How to Eliminate Image Flickering While Loading in a React Component

Currently, I am developing a React component that takes an imageUrl and displays it on a canvas with a deliberate 2-second delay to mimic loading time for larger images. However, I have encountered a problem: when the imageUrl changes in the parent compone ...

Encountering a proxy error while attempting to create an account or log in, with no network

Embarking on my first web development journey, I utilized React-Redux to craft a React.js application within the client folder. For the backend code, I employed Node.js and MongoDb as my database. This project represents a significant milestone in my lear ...

Why is it that the edit or delete button is not functioning when I attempt to click on the next page?

Having an issue with my script. It works fine for editing and deleting on the first page, but when I navigate to the next page, those functionalities stop working. Can anyone help me troubleshoot this problem? <script> $(function(){ $(&ap ...

Remove Chosen Pictures (Checkbox/PHP/MySQL)

I am currently displaying images from a Database using the following HTML code: <li> <input type="checkbox" id="1" /> <a rel="gallery_group" href="images/big/1.jpg" title="Image 1"> <img src="images/small/1.jpg" alt="" ...