Javascript retrieve the style of an element in every possible state

I am interested in retrieving the line height of an element; it's a simple task.

Here is a method that I know works:

console.log(document.getElementById("myDiv").style.lineHeight);

console.log($("#myDiv").css('lineHeight'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv" style="line-height:30px;">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
  survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>

My main question is - can we obtain the line height of an element if the style is applied to the parent element?

console.log(document.getElementById("myDiv").style.lineHeight);

console.log($("#myDiv").css('lineHeight'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="line-height:30px;">
  <div id="myDiv">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </div>
</div>

Alternatively, how do we retrieve it if it's using the default value from the browser?

console.log(document.getElementById("myDiv").style.lineHeight);

console.log($("#myDiv").css('lineHeight'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div id="myDiv">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </div>
</div>

Despite jQuery providing the desired value, I specifically require a solution using javascript.

Any assistance on this matter would be greatly appreciated.

Answer №1

To retrieve the style, you can utilize the getComputedStyle method which is commonly employed in jQuery.

//console.log(document.getElementById("myDiv").style.lineHeight);

//console.log($("#myDiv").css('lineHeight'));


var elem = document.getElementById("myDiv");
var view = elem.ownerDocument.defaultView;

console.log(view.getComputedStyle( elem )['line-height']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div id="myDiv">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </div>
</div>

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

I require the box element within my section element to have a full-width layout

Looking at the code in the image, you can see that I am using MUI components. Within a section, there is a box containing navigation filter links. The red part represents the section, while the white inside is the navigation link bar. My goal is for this b ...

The art of organizing dates and times

Need help with formatting a datetime that is retrieved from the database. The current format is as follows: 2012-06-11 21:39:54 I would like to display it in the format of June 11. Any suggestions on how this can be achieved? Thank you! ...

Having difficulty executing the npm test command for my Angular 2 application

I am currently working on an Angular 2 application, and I am fairly new to it. I have set it up with Cordova app and run it through npm. The app starts without any errors and runs smoothly. However, when I try to run the tests using node (i.e., npm test), ...

What is the method for accessing an app from a file other than server.js?

I am dealing with two different files: file1.js const app = express(); require('./file1/config/customConfigurations').customSettings() .then((settings) => { app.locals.customSettings = settings; console.log(app.locals.customSettings) ...

Placing an item inside the container without exceeding its vertical limit

Check out this jsfiddle - http://jsfiddle.net/az47U/3/ - where you'll find a Gallery div along with a Canvas div, both located within the body. These divs have been absolutely positioned to not affect the overall body height. I've set the body he ...

Caution: Potential Unresolved Promise Rejection Detected (ID: 21) - Error: Undefined is not a valid object when trying to evaluate 'res.json'

ERROR Getting an Unhandled Promise Rejection (id: 21): TypeError: undefined is not an object (evaluating 'res.json'). Any suggestions on fixing this issue in my code? I've checked the logs for user and loggeduserobj, and they seem to be cor ...

The output of server.address() method in Node.js is ::

My memory serves me right, a few days back it was showing "localhost". I'm puzzled as to what altered server.address().address to now return double colons (::). According to my research, it seems to be returning an IPv6 address (::) because it's ...

Error Encountered when Using JQuery AJAX: Unexpected Identifier Syntax Issue

I've been struggling with a strange error for quite some time now. I want to believe that this is one of those errors where the solution will magically appear, but only time will tell. Here's the piece of code causing the issue: var images = ...

Bringing a JavaScript file into an Ionic/Angular 2 project

I have been attempting to integrate a simple JS library into Angular 2. The library in question is JIC.js. var jic = { /** * This function takes an Image Object (JPG or PNG) and returns a compressed new Image Object * @param {Ima ...

Leverage the power of the YouTube API to determine if a video is able to be embedded

As I delve into the YouTube Data API v3 to determine if a particular video is embeddable, I have come across the status.embeddable property that seems crucial. By making a request like this: https://www.googleapis.com/youtube/v3/videos?id=63flkf3S1bE& ...

Extract information from an HTML table into PHP

I have an HTML table that is generated dynamically and I am looking to extract the data from it using the POST method. Is there a way to accomplish this? Are there any alternative methods you would suggest for achieving this goal? Below is a basic example ...

React - the constructor binding issue with 'this' keyword

I am a beginner in React and I am learning through creating a simple test application. However, I am facing an issue with "this" binding. I set up this app package yesterday using "create-react-app", so all the necessary plugins including babel should be u ...

Implementing conditional ng-show based on checkbox status in AngularJS

I have created this code to filter out the out-of-stock products using ng-show. When the checkbox is checked, only the available products should be displayed. HTML: <input type="checkbox" id="chkStock" value="Exclude Out of Stock" ng-model="exclude" / ...

React Router imports and renders multiple components

I'm currently working on developing a basic Login System. When I try to register, both components are loaded into the App Component. Here is my code: class App extends React.Component { render() { return ( <div className="row"> ...

Tips for displaying a Rails action without a layout in html format using Ajax

Is it possible to render the new action without the application layout and without altering the current code structure? class FoobarController < ApplicationController def new @foobar = Foobar.new end # ... end When a user clicks on = link_ ...

When encountering an "uncaught SyntaxError" in the $.parseJSON function, one may want to investigate

When using this jQuery function, I encounter an Uncaught SyntaxError: Unexpected token u error if the cookie $.cookie('chk_ar') is undefined. function checkBgNoise() { // checks background noise option state, // activates 'on' click i ...

Battle between Comet and Ajax polling

I'm looking to develop a chat similar to Facebook's chat feature. Using Comet would require more memory to maintain the connection. There seems to be a latency issue when using Ajax polling if requests are sent every 3-4 seconds. Considering t ...

Exploring the inheritance of directives and controllers within AngularJS

I'm struggling to grasp the concept of inheriting a parent controller from a directive. In my setup, I have a simple example with a controller named MainCrtl. This controller is responsible for creating and removing an array of directives called inner ...

The iframe is not adjusting its size in relation to the parent window

For more information, click here: http://jsfiddle.net/5HYve/ <div style="position: fixed; top:0; right:0; width:300px; height: 100%; text-align:justify; overflow:hidden;" class="chat-container"> <iframe id="chat_1" style="width:300px;height:1 ...

How to divide an HTML string into an array using PHP

I am in need of some assistance from you all. The issue I am facing involves dealing with a string of HTML that looks like this: <h4>Some title here</h4> <p>Lorem ipsum dolor</p> (some other HTML here) <h4>Some other title ...