Can you style an element with JavaScript without adding a style attribute? - javascript

When you write element.style = "..." in JavaScript in adds the style attribute to the element you add the style to. Is there a way to add a style without the style attribute, without any libraries?

If you can come up with a selector that targets the element, another option is to append a stylesheet that contains that selector:
const styleTag = document.head.appendChild(document.createElement('style'));
styleTag.textContent = 'div { color: blue; }';
<div>Some div</div>
It'd be more reliable if you're permitted to change the element in some way, like add a class or other attribute:
const div = document.querySelector('div');
const className = `_${('' + Math.random()).slice(2)}`;
div.classList.add(className);
const styleTag = document.head.appendChild(document.createElement('style'));
styleTag.textContent = `.${className} { color: blue; }`;
<div>Some div</div>

With JS, you can write anything to the DOM, including a <style> tag. So for example:
const el = document.getElementById('changeColor');
el.onclick = function(e) {
const s = document.createElement('style');
s.innerHTML = '.box { background-color: yellow; }';
document.querySelector('body').appendChild(s);
}
.box {
width: 150px;
height: 150px;
background-color: red;
color: white;
padding: 20px;
}
#changeColor {
margin: 10px 0;
}
<body>
<button type="button" id="changeColor">Change It</button>
<div class="box">This is a box</div>
</body>

Add a CSS class inside styles tags
Use the DOMContentLoaded event to add a class to the element when the document is loaded
Get the elment through its tag name
Use setAttribute method in vanillaJS to add the CSS class to your tag elment
In this way it could be more maintainable yoru code, because you change at css level and JS auntomaticly will put the value tanken from css class declared
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Example</title>
<style>
.styles {
color: red;
}
</style>
</head>
<body>
<p>Hello there</p>
<script>
let paragraph = document.querySelector("p")
document.addEventListener("DOMContentLoaded", () => {
paragraph.setAttribute("class", "styles")
})
</script>
</body>
</html>

Related

How to add a class name to a specific elements

how i can create a javascript code to add class name to specific divs only
for Exapmle : i want to add a class_name to from div5 to the end of all divs ?
try this
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
font-size: 25px;
box-sizing: border-box;
}
</style>
</head>
<body>
<p>Click the "Try it" button to add the "mystyle" class to the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is a DIV element.
</div>
<script>
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.add("mystyle");
}
</script>
</body>
</html>
If you're looking to add a class name from one div to others, I would recommend using JQuery. This can be done like so:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function changeColor(){
$( document ).ready(function() {
$("div").addClass("work");
});
}
</script>
<style>
.work {
color: red
}
</style>
<div style="width: 100%" class="work"><h1>Hello</h1></div>
<div style="width: 100%" class=""><h1>Hello</h1></div>
<button onclick="changeColor()">Change second color by inserting class!</button>
function applyClass(elem_position, tagname, classname)
{
var div_elems = document.querySelectorAll(tagname);
for (var i = elem_position-1; i < div_elems.length;i++)
{
div_elems[i].className=classname;
}
}
Usage
Applies class some_class to div elements starting from position 3
applyClass(3,'div','some_class');

How can I make my div appear with createElement

I am trying to make another div right under the existing div in the HTML
<html>
<head>
<title>
Media Player
</title>
<script src="script.js"></script>
</head>
<script>
makeOscarPlayer(document.getElementById("my-video"))
</script>
<body>
<div class="my-player">
Hello!
</div>
</body>
</html>
function makeOscarPlayer(){
var div = document.createElement("div");
div.innerHTML = `
hello
`
}
can someone explain to me what I am doing wrong? I am a self-taught developer sorry if my code is not perfectly organized still learning
You are calling the makeOscarPlayer() function before you are creating it.
You need to wrap the makeOscarPlayer() function declaration in a script tag.
You are passing in document.getElementById("my-video") as a parameter to makeOscarPlayer(), but there is no HTML element with an id of 'my-video'. You are giving the function a parameter of null, while the function declaration has no parameters.
You need to tell the script where to put the new element. To do that, you grab an existing element and use parentNode and insertBefore
Here is a barebones version that I got working for your reference:
<html>
<head>
<title>
Media Player
</title>
</head>
<script>
</script>
<body>
<div id="my-player">
Hello!
</div>
</body>
</html>
<script type="text/javascript">
function makeOscarPlayer(){
var div = document.createElement("div");
div.innerHTML = `hello`;
// This grabs the element that you want to create a new element by
var existingDiv = document.getElementById("my-player");
// This tells the script where to put the new element
existingDiv.parentNode.insertBefore( div, existingDiv.nextSibling);
}
// Must be called in the same script block or after the script holding the function declaration is loaded
makeOscarPlayer();
</script>
For more information on how parentNode and insertBefore work, see this Stack Overflow question
You need to append that new element to a specific parent, in your case to my-video.
The function appendChild appends the new element to a parent element.
function makeOscarPlayer(parent) {
var div = document.createElement("div");
div.innerHTML = 'Hello from Ele';
parent.appendChild(div);
}
makeOscarPlayer(document.getElementById("my-video"))
#my-player {
border: 1px dashed green;
padding: 5px;
margin: 5px;
width: 300px;
background-color: #f1f1f1
}
#my-video div {
border: 1px dashed green;
padding: 5px;
margin: 5px;
width: 200px;
font-weight: 700;
}
<div id="my-player">
Hello!
<div id="my-video">
</div>
</div>
It's a good start, but you're calling the function incorrectly and your function isn't adding anything to the page.
we use appendChild to add a node to the page.
In your function you create and add text to a div, but you don't return the node you made(and also you didn't close your line of code with a semi-colon so I added that too) but this should work:
<html>
<head>
<title>
Media Player
</title>
</head>
<body>
<div class="my-player">
Hello!
</div>
<script>
function makeOscarPlayer() {
var div = document.createElement("div");
div.innerHTML = `hello`;
return div;
}
document.getElementById("my-video").appendChild(makeOscarPlayer())
</script>
</body>
</html>
function makeOscarPlayer() {
var div = document.createElement("div");
div.innerHTML = `hello`;
return div;
}
document.getElementById("my-video").appendChild(makeOscarPlayer())
<html>
<head>
<title>
Media Player
</title>
</head>
<body>
<!-- added my-video div -->
<div id="my-video"></div>
<div class="my-player">
Hello!
</div>
</body>
</html>

Fading in and out CSS stylesheet with Javascript

I am trying to implement more elegant elements in my site using Javascript.
Snippet
<script>
function nightmode(){
var el = document.getElementById('myStyles'); // get stylesheet
if ( el !== null ) { // if it exists
el.parentNode.removeChild(el); // remove it
} else { // if not, add it
var oLink = document.createElement("link")
oLink.id = 'myStyles';
oLink.href = "nightmode3.css";
oLink.rel = "stylesheet";
oLink.type = "text/css";
document.body.appendChild(oLink);
}
}
</script>
That switches the site to nightmode. If you click the button, it switches nightmode on, or off. Simple enough.
However, I'd like a .5 second fadein/fadeout effect on each click, to make it less jarring. I've tried adding it via CSS, but that only works for fade in. How can I get both fade in and fade out effects?
Here are a few different ways to keep transitions working whenever you switch between styles. The underlying thing to keep in mind is that you have to have a transition rule available for the transition to happen. If you have it in one style but not the other, it will only happen whenever you change to the style that has it because otherwise there is no rule saying that there needs to be a transition.
<link> Swapping Method
Basically, make sure that the transition rules are always available. If they are in your night/day stylesheet but not other, then there is no longer a rule to transition. That's why it would only work whenever you fade in.
Ideally though, you would probably want both sets of rules in a single file and then change between the active styles using a class on the <body> tag. However, there are certainly use cases where you might want to still use two separate stylesheets that aren't both loaded simultaneously. For example a high contrast stylesheet that might not be used by all users would waste memory. However, I'd still probably use the class attribute on the <body> tag in case I ever wanted to combine them.
index.html
<html>
<head>
<title>CSS Test</title>
<link rel="stylesheet" href="base.css">
<script src="index.js"></script>
</head>
<body>
<main>
<h1>Hello!</h1>
<p>I am text</p>
<ul>
<li>
<button id="day_mode">Day</button>
</li>
<li>
<button id="night_mode">Night</button>
</li>
</ul>
</main>
</body>
</html>
index.js
/*jslint browser:true*/
(function () {
"use strict";
function addStylesheet(name, loc) {
var sheet = document.createElement("link");
sheet.id = name;
sheet.href = loc;
sheet.rel = "stylesheet";
sheet.type = "text/css";
document.head.appendChild(sheet);
return sheet;
}
function removeStylesheet(sheet) {
sheet.parentNode.removeChild(sheet);
//document.getElementById(name).removeChild();
}
function go() {
var dayButton = document.getElementById("day_mode"),
nightButton = document.getElementById("night_mode"),
daySheet,
nightSheet;
dayButton.addEventListener("click", function (e) {
e.preventDefault();
if (!daySheet) {
if (nightSheet) {
removeStylesheet(nightSheet);
nightSheet = null;
}
daySheet = addStylesheet("day", "day.css");
}
});
nightButton.addEventListener("click", function (e) {
e.preventDefault();
if (!nightSheet) {
if (daySheet) {
removeStylesheet(daySheet);
daySheet = null;
}
nightSheet = addStylesheet("night", "night.css");
}
});
}
document.addEventListener("DOMContentLoaded", go);
}());
base.css
h1 {
transition: color 1s;
}
p {
transition: background-color 1s, color 1s;
}
day.css
h1 {
color: orange;
}
p {
background-color: yellow;
color: red;
}
night.css
h1 {
color: blue;
}
p {
background-color: black;
color: blue;
}
<body> Class Namespacing
If you do want to try the <body> class method, here is a short implementation showing how to do that.
The basics of this is that you have a namespace for each version, day/night, of the CSS that you want to use and you prefix those mode rules with the relevant namespace.
Then, using JavaScript, you would remove or add the namespace class from your <body> tag using document.body.classList.add() and document.body.classList.remove().
/*jslint browser:true*/
(function() {
"use strict";
function go() {
var dayButton = document.getElementById("day_mode"),
nightButton = document.getElementById("night_mode");
dayButton.addEventListener("click", function(e) {
e.preventDefault();
document.body.classList.remove("night");
document.body.classList.add("day");
});
nightButton.addEventListener("click", function(e) {
e.preventDefault();
document.body.classList.remove("day");
document.body.classList.add("night");
});
}
document.addEventListener("DOMContentLoaded", go);
}());
h1 {
transition: color 1s;
}
p {
transition: background-color 1s, color 1s;
}
body.day h1 {
color: orange;
}
body.day p {
background-color: yellow;
color: red;
}
body.night h1 {
color: blue;
}
body.night p {
background-color: black;
color: blue;
}
<html>
<head>
<title>CSS Test</title>
<link rel="stylesheet" href="index2.css">
<script src="index2.js"></script>
</head>
<body class="day">
<main>
<h1>Hello!</h1>
<p>I am text</p>
<ul>
<li>
<button id="day_mode">Day</button>
</li>
<li>
<button id="night_mode">Night</button>
</li>
</ul>
</main>
</body>
</html>
Alternate Stylesheet Relation
One other thing to note, is that if you use the <link ... rel="stylesheet alternate" ...> approach, the transitions will also still work. I'm not sure what browsers still provide a means for users to switch their preferred rendering style manually. Chrome does not provide a way, but FireFox does. See the below screenshot.
Here is the markup I'm using for my <head> element.
<head>
<title>CSS Test</title>
<link rel="stylesheet" href="base.css">
<link rel="stylesheet" href="day.css" title="Day">
<link rel="stylesheet alternate" href="night.css" title="Night">
<script src="index.js"></script>
</head>

change css attributes of child when parent class is changed

I have a div inside another div. the parent has a particular class name that doesn't specifically have any css applied to it. the child element has css applied to it, specifically it's background color. so it looks like this...
<div id='myparent' class='someclass'>
<div id='mychild' class='somebgcolor'></div>
</div>
what I want to do is change the background color of the child div when the class of the parent div is changed. so I'm changing the class of the parent with this javascript...
document.getElementById('myparent').className = 'someotherclass';
and in my css...
.someclass .somebgcolor {
background-color: #369;
}
.someotherclass .somebgcolor {
background-color: #401;
}
but it doesn't work. for starters, the initial background color isn't even applied, and no background color is applied when i update the class of the parent div. am i missing something fundamental to the way applying css to nested elements works?
I don't think you're missing anything. I just tried it out and it works fine:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.someOtherClass {
background-color: yellow;
}
.someOtherClass .someBgColor {
background-color: red;
}
</style>
</head>
<body>
<div id="myParent" class="someClass">
<div id='myChild' class="someBgColor">
asdasadasd
</div>
</div>
<script>
var parent = document.getElementById('myParent');
parent.className = "someOtherClass";
</script>
</body>
</html>

IE not applying base to background image definitions in css

IE (tested 7-10) is not applying the base (an absolute URL) to background images within a style tag, resulting in 404. This only happens when the code is injected using innerHTML (a requirement of the larger application this belongs to). It applies the base to all other elements as seen in the example.
Any suggestions?
Edit 2014/01/13 This is fixed if I remove the style tags from the HTML string and manually append them to the header. Would like to know if this is the only answer. Based upon this solution: How to create a <style> tag with Javascript
<!DOCTYPE html>
<html>
<head>
<title>base test</title>
<base href="http://absoluteurl.com/">
</head>
<body>
<div id="container"></div>
</body>
<script>
var html = "First Node<br>Second Node.<br><style>#bkgdiv {background-image: url(media/ex_amp.jpg); border: 1px solid #f00; width: 200px; height: 200px;}</style><div id=\"bkgdiv\">DIV w/ Background</div><br><img src=\"media/ex_amp.jpg\">";
document.getElementById('container').innerHTML = html;
</script>
</html>
Have you tried the jQuery appendTo method?
Inline style elements have to be removed from the HTML string, added to a style element object, and then appended to the head.
<!DOCTYPE html>
<html>
<head>
<title>base test</title>
<base href="http://absoluteurl.com/">
</head>
<body>
<div id="container"></div>
</body>
<script>
var html = "First Node<br>Second Node.<br><style>#bkgdiv {background-image: url(media/ex_amp.jpg); border: 1px solid #f00; width: 200px; height: 200px;}</style><div id=\"bkgdiv\">DIV w/ Background</div><br><img src=\"media/ex_amp.jpg\">";
var head = document.getElementsByName('head')[0];
content.html = content.html.replace(/<style(.|\n)*?>(.|\n)*?<\/style>/ig, function(match) {
var css = match.replace(/<\/?style(.|\n)*?>/ig, "");
style = document.createElement('style');
style.type = 'text/css';
if(style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
return "";
});
document.getElementById('container').innerHTML = html;
</script>
</html>

Categories