Подключить css при помощи js

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.

Источник

Подключение style.css в javascript файле?

Привет!
Есть cтраница index.html и к ней подключается много файлов (css, js).
Как можно организовать подключение всех файлов одной строкой?
Возможен ли вариант прописать все подключения в js файле и вместо большой бороды указывать только одну строку типа
?
p.s. Это нужно, когда много html сайтов и ко всем нужно прицепить свои стили и настройки и не надо копировать бороду, вставил всего 1 подключение и все. Т.е. упор на не на качество кода, а на скорость подключения своих заранее подготовленных файлов.

let head = window.document.getElementsByTagName('head')[0] function includeCSS(aFile, aRel)

Александр Сорокин,
head - это переменная секции head документа html
includeCSS - это JS функция которая подключает указанный файл к html документу

пример использования
includeCSS('MyPage.css'); // это подключит к текущему html документу файл стилей MyPage.css
эту функцию вы можете вызывать в цикле где будете подключать из списка css файлы.

для подключения JS файла к документу необходима другая функция

function loadJS(aFile, aAsync)< let script = window.document.createElement('script') script.type = 'text/javascript' script.src = aFile script.async = aAsync || false head.appendChild(script) >
function includeCSS(aFile) < let style = window.document.createElement('link') style.href = aFile style.rel = aRel || 'stylesheet' head.appendChild(style) >includeCSS('style.css') includeCSS('main/style.css') includeCSS('www.site.ru/style.css')

с подключением js аналогично как и с css

Источник

Как добавить css свойство в js

Для того, чтобы добавить CSS свойство в JS нам на помощь могут прийти следующие возможности:

Обратиться через свойство style:

const divContainer = document.getElementById("container"); // находим элемент в DOM - дереве divContainer.style.backgroundColor = "blue"; // устанавливаем цвет фона элемента на цвет blue 
divContainer.style["background-color"] = "yellow"; // устанавливаем цвет фона на yellow 

Кстати, свойство можно не только задать, но и удалить. Для этого достаточно присвоить пустую строку:

divContainer.style.backgroundColor = ''; 

Обратиться к элементу через метод setProperty():

divContainer.style.setProperty("background-color", "green"); 

Установить атрибут и свойство целиком с помощью метода setAttribute():

const divContainer = document.getElementById("container"); divContainer.setAttribute("style", "background-color: lightgray"); 

Документация:

Источник

Читайте также:  Best sites to learn html
Оцените статью