Add stylesheet to html javascript

Динамическое добавление таблицы стилей CSS на HTML-страницу с помощью JavaScript/jQuery.

В этом посте мы обсудим, как динамически добавить таблицу стилей CSS на HTML-страницу с помощью JavaScript и jQuery.

1. Использование jQuery

Если вы работаете с jQuery, вы можете использовать .appendTo() метод для добавления таблицы стилей в конце элемент текущего документа. Вот как это сделать:

Здесь альтернативная версия с использованием .append() метод:

С $.ajax() метод, вы можете загрузить CSS с сервера и заключить содержимое в теги и, наконец, добавьте его в конец элемент текущего документа. Следующий код демонстрирует это, динамически загружая библиотеку начальной загрузки.

Здесь альтернативная версия с использованием .load() метод:

2. Использование JavaScript

В ванильном JavaScript вы можете использовать собственный createElement() способ создания таблицы стилей и appendChild() способ добавления таблицы стилей в конец элемент текущего документа. Вот как мы можем это сделать:

Кроме того, вы можете поиграть с innerHTML свойство Document.head .

Это все о динамическом добавлении таблицы стилей CSS на HTML-страницу с использованием JavaScript и jQuery.

Средний рейтинг 4.58 /5. Подсчет голосов: 31

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

How to set CSS styles using JavaScript

In my previous article, we looked at different ways to get style information from an HTML element using JavaScript. Today, you’ll learn how to apply CSS styles to HTML elements with JavaScript.

Let us say we have the following element:

div class="pizza">Hot, spicy, pizza 🍕div> 

Now, we want to change its text, background colors, and font style CSS properties using JavaScript. What should we do? There are multiple options available in JavaScript.

The easiest and straightforward way to change the CSS styles of an element with JavaScript is by using the DOM style property. All you need to do is fetch the element from DOM and change its inline styles:

const pizza = document.querySelector('.pizza') // change the text color to white pizza.style.color = 'white' // set background color to blue pizza.style.backgroundColor = 'blue' // change font style to italic pizza.style.fontStyle = 'italic' 

The style property uses the camel-case naming conventions for CSS properties and applies styles inline to the element:

div class="pizza" style="color: white; background-color: blue; font-style: italic;">Hot, spicy, pizza 🍕div> 

Another way is to create a

const style = document.createElement('style') 

Finally, append the style element to the DOM. To do this, get the tag using document.head , and then call the appendChild() method on it to append the style element:

document.head.appendChild(style) 
// create an element const style = document.createElement('style') // add CSS styles style.innerHTML = ` .pizza ` // append to DOM document.head.appendChild(style) 

The CSS Object Model is a set of APIs allowing the manipulation of CSS from JavaScript. It is much like the DOM, but for the CSS rather than the HTML. It allows users to read and modify [the] CSS style dynamically.

The CSSStyleSheet.insertRule() method inserts a new CSS rule to a stylesheet. Here is how you can use this method to add styles to the above HTML element:

// create an new style const style = document.createElement('style') // append to DOM document.head.appendChild(style) // insert CSS Rule style.sheet.insertRule(` .pizza `) 

It is not really required to create a new element. You can use existing elements as well as external stylesheets to add CSS rules using insertRule() . The insertRule() method works in all modern browsers, including Internet Explorer 9 and higher.

Constructable Stylesheets is a modern way of creating and distributing reusable styles when working with the Shadow DOM. Here is an example that creates a Constructable Stylesheets and appends it to the Shadow DOM:

// create a new shared stylesheet const sheet = new CSSStyleSheet() // add CSS styles sheet.replaceSync(` .pizza `) // apply the stylesheet to a document document.adoptedStyleSheets = [sheet] 

In this article, we looked at four ways to add CSS styles to an HTML element in JavaScript. So, which method should you use? It depends on what you want to achieve by dynamically changing the CSS. If you only want to modify CSS styles for a single element, it is better to use the style property. This property changes the inline styles for a specific HTML element without affecting global styles. If you want to apply a style to a set of HTML elements, create a new tag with the necessary CSS properties and append it to the document. Read Next: How to add multiple CSS styles using JavaScript ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Javascript Set CSS Set CSS styles with javascript

2. Global styles

 var style = document.createElement('style'); style.innerHTML = ` #target < color: blueviolet; >`; document.head.appendChild(style); 

global styles

3. CSSOM insertRule

 var style = document.createElement('style'); document.head.appendChild(style); style.sheet.insertRule('#target '); 

insertRule

While it might look similar to the 2nd option, it's definitely different.
As you can see in Chrome devtools, tag is empty, but the style (darkseagreen color) is applied to the element. Also the color can't be changed via devtools because Chrome doesn't allow editing dynamic CSS styles. Actually such behavior was the motivation to write this post. A popular CSS-in-JS library Styled Components use this feature to inject styles in production mode because of performance. This feature might be undesirable in specific projects or environments and some folks complain about it in the project's issues.

4. Constructable Stylesheets (July 2019 update)

// Create our shared stylesheet: const sheet = new CSSStyleSheet(); sheet.replaceSync('#target '); // Apply the stylesheet to a document: document.adoptedStyleSheets = [sheet]; 

More details are here.
This option is only valid for Chrome, so use with caution. Do you know other options to add styles with javascript? What is your preferred option these days? Thanks for reading!

Источник

Читайте также:  My Iframe Page
Оцените статью