Home > Web Front-end > CSS Tutorial > How to Retrieve CSS Values from External Stylesheets Without Elements in Javascript/jQuery?

How to Retrieve CSS Values from External Stylesheets Without Elements in Javascript/jQuery?

Susan Sarandon
Release: 2024-11-16 09:36:03
Original
499 people have browsed it

How to Retrieve CSS Values from External Stylesheets Without Elements in Javascript/jQuery?

Retrieving CSS Values from External Stylesheets with Javascript/jQuery

In web development, it may be necessary to access CSS values from an external stylesheet without having the corresponding HTML element physically present on the page. This scenario often arises when generating content dynamically.

The commonly used jQuery method $('element').css('property') relies on the element being rendered in the page. However, to determine the CSS property value before the element is created, an alternative approach is required.

Using a Surrogate Element

One solution is to create a temporary, hidden surrogate element and read its computed style. jQuery's $("

").hide().appendTo("body") creates a hidden paragraph element in the page body. You can then invoke $p.css("color") to retrieve the CSS color property value.

Example Code

// Scoping function to avoid creating a global
(function() {
    var $p = $("<p></p>").hide().appendTo("body");
    console.log($p.css("color"));
    $p.remove();
})();
Copy after login

Note: In this example, the external CSS file must define the "p" element with the desired style properties.

The above is the detailed content of How to Retrieve CSS Values from External Stylesheets Without Elements in Javascript/jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template