как изменять содержимое тега style
Хочу изменять содержимое тега style через javascript, но что-то не идёт.
Я добавляю тег style в .content и хочу, чтобы применились стили для .content которые я написал в input
function getElemWithClass(tag, ...className) {
const node = document.createElement(tag);
className.forEach((_className) => {
node.classList.add(_className);
});
return node;
}
function createStyle(content) {
let style = content.querySelector('.my__style');
if (style !== null) {
style.remove();
}
style = getElemWithClass('style', 'my__style');
content.prepend(style);
return style;
}
const content = document.querySelector('.content');
const input = document.querySelector('.input');
input.addEventListener('input', (e) => {
const value = e.target.value;
const style = createStyle(content);
style.cssText = value;
});
*,
*:before,
*:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
margin: 0;
padding: 0;
}
.block {
width: 50px;
height: 50px;
background-color: red;
color: white;
}
.input {
border: 1px solid black;
max-width: 200px;
margin-bottom: 10px;
font-size: 20px;
}
<input type="text" class="input">
<div class="content">
<div class="block">
1
</div>
</div>
Ответы (1 шт):
Автор решения: Igor
→ Ссылка
Введите .block{color:black;}.
function getElemWithClass(tag, ...className) {
const node = document.createElement(tag);
className.forEach((_className) => {
node.classList.add(_className);
});
return node;
}
function createStyle(content) {
let style = content.querySelector('.my__style');
if (style !== null) {
style.remove();
}
style = getElemWithClass('style', 'my__style');
content.prepend(style);
return style;
}
const content = document.querySelector('.content');
const input = document.querySelector('.input');
input.addEventListener('input', (e) => {
const value = e.target.value;
const style = createStyle(content);
style.innerText = value;
});
*,
*:before,
*:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
margin: 0;
padding: 0;
}
.block {
width: 50px;
height: 50px;
background-color: red;
color: white;
}
.input {
border: 1px solid black;
max-width: 200px;
margin-bottom: 10px;
font-size: 20px;
}
<input type="text" class="input">
<div class="content">
<div class="block">
1
</div>
</div>