Changing css style sheet with javascript - javascript

I have the following:
<style>
.el {color: blue;}
</style>
<div class="el">bla bla</div>
<div class="el">bla bla 123</div>
And i need to use JavaScript to change the color in .el.
I know about document.styleSheets but that seems kind of crude, having to loop search for the class i want to change it that way. Isn't there some better (lighter) way to do this nowadays? Something like
document.stylesheets.getclass('.el').color = 'red';
Thanks.

You're on the right track. The method you're looking for is getElementsByClassName, not getClass. It returns an array, and then you simply loop through the array and assign the new color.
var el = document.getElementsByClassName('el'),
i;
for (i = 0; i < el.length; i += 1) {
el[i].style.color = 'red';
}
Demo
P.S., obviously, this changes the style, not the stylesheet.

Try this:
var elem = document.getElementsByClassName('el');
for (var i = 0; i < elem.length; i++) {
elem[i].style.color = '#aaaaaa';
}

Related

Change inline css of an element without an id or class

It's pretty simple to change the style of an element when it has a class. I thought it would be simple to change the style of an element that has no class or id too, but I haven't been able to figure it out.
The html page looks something like this:
<!DOCTYPE html>
<html>
<head>
<title>ExamplePage</title>
</head>
<body>
<h1>Lorem ipsum</h1>
<p style="display: none">The style shouldn't change</p>
<section class="container_class">
<p style="display: none">The display part of the inline css should be deleted or modified to inline</p>
<p style="display: none">The display part of the inline css should be deleted or modified to inline</p>
<p style="display: none">The display part of the inline css should be deleted or modified to inline</p>
</section>
<p style="display: none">The style shouldn't change</p>
</body>
</html>
Since I'm trying to build a google chrome extension I've been using contentscripts.
I haven't figured out how to select the specific element although I have seen something similar to this idea.
I've searched the internet on how to select a specific element based on the inline css. I couldn't find anything helpful.
This is my content.js:
var ps = document.querySelectorAll("section.container_class > p");
var i;
for (i = 0; i < ps.length; i++) {
ps.style.display = "inline";
}
I'm new to coding in javascript, so the code might not make sense at all. It's just an idea on how to change the inline css. I'm trying to learn by doing a mini-project like this.
You're nearly there.
The bug is in the for loop. It should be:
var ps = document.querySelectorAll("section.container_class > p");
var i;
for (i = 0; i < ps.length; i++) {
ps[i].style.display = "inline";
}
Note the square bracket array access notation on the ps variable.
ie. for every iteration of the loop, access the ith index of the array ps.
"document.querySelectorAll" returns an Array containing all the elements that you have specified (in this case: "section.container_class > p"). So when you want to iterate through the entire Array you will have to use an index.
Basically all you forgot was to add [i] in your block of code.
var ps = document.querySelectorAll("section.container_class > p");
var i;
for (i = 0; i < ps.length; i++) {
ps[i].style.display = "inline";
}
However you should try to use the let and const keywords instead of var.
Also i is defined as a global variable and you don't want that because it might interfer with locally defined variables. So instead you should declare it in the for-loop "head".
A newer version might look something like this:
const PS = document.querySelectorAll("section.container_class > p");
for (let i = 0; i < ps.length; i++) ps[i].style.display = "inline";
var ps is defined to array as it selected for querySelectorAll. Seems there is no number for ps array in for loop.
var ps = document.querySelectorAll("section.container_class > p");
var i;
for (i = 0; i < ps.length; i++) {
//Here should be array num.
ps[i].style.display = "inline";
}

jQuery Replace With only works once for an object reference

I'm having a strange issue with replaceWith (or more likely with object referencing).
I am trying to create a kind of table of rows that either have empty slots or full slots. As a demonstration I made this simple fiddle. http://jsfiddle.net/Ltxtvyn3/3/ In this fiddle 4 empty slots are initialized. Then one is filled. Then the same one should be emptied. But instead it is remaining filled. It is as if I can only use replaceWith once, or I am not understanding something about my object references.
HTML
<div class = "slot empty">Empty</div>
<div class = "slot full">Full</div>
<div class = "wrapper"></div>
CSS
.slot{
width:50px;
height:50px;
display:none;
}
.empty{
background-color:red;
}
.full{
background-color:blue;
}
Javascript
var wrapper = $('.wrapper');
var empty = $('.slot.empty');
var full = $('.slot.full');
var slots = {};
for(var i = 0; i < 4; i++){
slots[i] = empty.clone().show();
wrapper.append(slots[i]);
}
function fillSlot(id){
slots[id].replaceWith(full.clone().show());
}
function emptySlot(id){
slots[id].replaceWith(empty.clone().show());
}
fillSlot(1);
emptySlot(1);
I am hoping that the object var slots maintains a reference to the divs and I'm not sure if it is doing that or not.
No, it's not keeping a reference, but you can fix this pretty easily.
Here's some running code:
var wrapper = $('.wrapper');
var empty = $('.slot.empty');
var full = $('.slot.full');
for(var i = 0; i < 4; i++){
wrapper.append(empty.clone().show());
}
function fillSlot(id){
$(".wrapper .slot").eq(id).replaceWith(full.clone().show());
}
function emptySlot(id){
$(".wrapper .slot").eq(id).replaceWith(empty.clone().show());
}
fillSlot(1);
setTimeout(function() {
emptySlot(1);
}, 2000);
.slot{
width:50px;
height:50px;
display:none;
}
.empty{
background-color:red;
}
.full{
background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class = "slot empty">Empty</div>
<div class = "slot full">Full</div>
<div class = "wrapper"></div>
Thanks for the answers. I know understand why the object doesn't keep a reference, and I really wanted that to be the case. I simply added a wrapper slot and then I will affect the contents of the wrapper. That way I always have a reference to the slot.
HTML
<div class="slot-content empty">Empty</div>
<div class="slot-content full">Full</div>
<div class = "slot"></div>
<div id="wrapper"></div>
Javascript
var wrapper = $('#wrapper');
var slot = $('.slot');
var empty = $('.slot-content.empty');
var full = $('.slot-content.full');
var slots = {};
for(var i = 0; i < 4; i++){
slots[i] = slot.clone().show();
slots[i].html(empty.clone().show());
wrapper.append(slots[i]);
}
function fillSlot(id){
slots[id].html(full.clone().show());
slots[id].find('.slot-content').html('hello');
}
function emptySlot(id){
slots[id].html(empty.clone().show());
}
fillSlot(1);
emptySlot(1);
fillSlot(2);
UPDATED
Your code work fine just if you change the selection method and you don't want slots list no more.
Replace :
function fillSlot(id){
slots[id].replaceWith(full.clone().show());
}
function emptySlot(id){
slots[id].replaceWith(empty.clone().show());
}
BY :
function fillSlot(id){
wrapper.children().eq(id).replaceWith(full.clone().show());
}
function emptySlot(id){
wrapper.children().eq(id).replaceWith(empty.clone().show());
}
Selecting directly from wrapper what means selecting from fresh DOM. that will fix the problem, take a look at updated fiddle bellow.
Updated JSFiddle
The problem is slots[i] isn't pointing to the div - so replaceWith won't pick the right item. Update the loop as follows (adding slots[i] = wrapper.find(':last-child') ):
for(var i = 0; i < 4; i++){
slots[i] = empty.clone().show();
wrapper.append(slots[i]);
slots[i] = wrapper.find(':last-child')
}
Actually this may make the code a little easier to understand (replace loop with this instead)
for(var i = 0; i < 4; i++){
wrapper.append(empty.clone().show());
slots[i] = wrapper.find(':last-child')
}
Tested and works on FF..
It's not keeping a reference to the DOM element. If you still want to use the array, then you can just repopulate the list every time you update one of its elements. Not terribly efficient, but I suppose it saves you from keeping state in the DOM.
function redraw() {
$('.wrapper').empty();
for(var i = 0; i < 4; i++){
wrapper.append(slots[i]);
}
}
JSFiddle

Change color for every second ul li with a "for loop"

I am learning javascript in codecademy and so far I understand how alot of things work. Sadly they dont explain how to target an elements color or how to target elements / selectors / divs.
I am testing out my knowledge. What I am trying is to give every second list item the color red by using the for loop.
How do I do this?
var listColor = function(){
var color = style.("red");
var list = getElementsByTagName("li");
for (i = 0; i < list.length; i + 2;) {
list === color
}
];
listColor();
and here my http://jsfiddle.net/Lr8nZ/15/
UPDATED JSfiddle but still not working http://jsfiddle.net/Lr8nZ/23/
so basically:
Red,
Black,
Red,
Black
Something do like this.
var listColor = function(){
var list = document.getElementsByTagName("li");
for (i = 0; i < list.length; i++) {
if(i%2==0)
list[i].style="color:red";
else
list[i].style="color:blue";
}
}
listColor();
You have a few syntax errors, but you can do this:
var listColor = function() {
var list = document.getElementsByTagName('li');
for (var i = 0, l = list.length; i < l; i++) {
if (i % 2 === 0) {
list[i].style.color = 'red';
}
}
};
// Or...
var listColor = function() {
var list = document.getElementsByTagName('li');
for (var i = 0, l = list.length; i < l; i += 2) {
list[i + 1].style.color = 'red';
}
};
listColor();
When you increment i make sure you're updating its value with i++ or i += 1, or you'll create an endless loop.
i % 2 uses the % modulus operator. It's the remainder you would get from dividing the two numbers. Even numbers divide evenly by 2, so the remainder will be 0, which we check for.
The property you were looking for is called style. It has a property called color which we set to the string 'red' in this case.
try this
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
index=1;
$("#temp li").each(function(){
if(index%2==0)
{
$(this).css("color","red")
}
index++;
});
})
</script>
<style>
</style>
</head>
<body>
<ul id='temp'>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
</body>
</html>
Try using a console to see the errors in your code. It's a tool that's indispensible for any js coder. Here's the updated fiddle http://jsfiddle.net/Lr8nZ/24/
The first thing which you notice is style.color('red'). For this line to be even valid js, there has to be a style object defined. Otherwise it will search for it on window which always leads to confusion.
Another thing is note how we have to actually assign the new value to i in for loop' third condition. Just mentioning i+2 will not work because i will stay the same resulting in an infinite loop.
Again, fire up web console. Generally, you do that by right clicking on page > Inspect > Web console.

CSS style to inline style via JavaScript

I want to add all CSS styles of a specific element to its inline style attribute. For example:
I have:
<div id="d"></div>
and:
#d { background: #444444; width: 50px; height: 20px; display: inline-block; }
Now I want a JavaScript function that turns my div into this:
<div id="d" style="background: #444444; width: 50px; height: 20px; display: inline-block;"></div>
Please help me. And, by the way, I don't want any CSS styles to re-write any existing inline style.
You can do something like this:
function applyStyle(el) {
s = getComputedStyle(el);
for (let key in s) {
let prop = key.replace(/\-([a-z])/g, v => v[1].toUpperCase());
el.style[prop] = s[key];
}
}
let x = document.getElementById('my-id');
applyStyle(x);
Where x is the element you want to apply the style to.
Basically this function gets the computed style of the element and then copies each property (like padding, background, color, etc.) to the inline style of the element.
I don't know why you need to do this, but it's a really dirty approach in my opinion. I would personally advise against it.
It appears this library will do what you're looking for: https://github.com/lukehorvat/computed-style-to-inline-style
Convert a HTML element's computed CSS to inline CSS.
Uses Window.getComputedStyle internally.
This one?
function transferComputedStyle(node) {
var cs = getComputedStyle(node, null);
var i;
for (i = 0; i < cs.length; i++) {
var s = cs[i] + "";
node.style[s] = cs[s];
}
}
function transferAll() {
var all = document.getElementsByTagName("*");
var i;
for (i = 0; i < all.length; i++) {
transferComputedStyle(all[i]);
}
}
Simply call transferAll onload, or whereever.
I think the issue with the accepted answer (thank you for that!) is that one of the properties it tries to transfer on the element style from the Computed Style is the cssText.
If we exclude from the transfer cssText and also other properties that are actually methods, it works!
So building on the accepted answer and this answer, I've got:
var el = document.querySelector("#answer-25097808 > div > div.answercell.post-layout--right > div.s-prose.js-post-body > pre"); // change yourId to id of your element, or you can write “body” and it will convert all document
var els = el.getElementsByTagName("*");
for(var i = -1, l = els.length; ++i < l;){
el = els[i]
s = getComputedStyle(el)
for (let styleKey in el.style) {
for (let computedStyleKey in s) {
let computedStyleKeyCamelCase = computedStyleKey.replace(/\-([a-z])/g, v => v[1].toUpperCase());
if ((typeof el.style[styleKey] != "function") && (styleKey != 'cssText')){
if(styleKey == computedStyleKeyCamelCase) {
el.style[styleKey] = s[computedStyleKey];
}
}
}
}
}
P.S.: the above code should run in the Developer Tools console (tried it in Chrome)
Using jQuery it can be done easily. Here is the sample code:
If you are new in jQuery and you don't know how to add and work then follow this link
$(document).ready(function(){
$("#d").css('background-color', '#444444').css('width', '50px').css('height', '20px').css('display', 'inline-block');
});
For javascript code I am not confident but for jQuery I am sure that it will work.
Correct me if I am wrong.

Getting an element by id every time I loop through

So my issue is, whenever I run this loop, it only grabs the changes to the element on the first flip through. Is there a way to make it make those changes every time?
<script>
for ( i=0; i<5; i++){
document.write('<div id=\"blah\" >text</div>');
var b = document.getElementById("blah");
b.style.width ="200px";
b.style.backgroundColor="yellow";
}
</script>
id has to be unique in a document. hence the issue. The DOM would return only 1 node even if there are multiple matches.
You can do something like this:
for (var i=0; i<5; i++){
var div = '<div class="blah" >text</div>';
div.style.width ="200px";
div.style.backgroundColor="yellow";
document.write(div);
}
I have two ideas to overcome this. The first is to create the element, change its style, and append it.
<script type="text/javascript">
for (var i = 0; i < 5; i++) {
var div = document.createElement("div");
div.style.width = "200px";
div.style.backgroundColor = "yellow";
document.appendChild(div);
}
</script>
The other idea is that you don't need a reference to the DOM element, because you're only changing style, so you can apply the style with CSS. For example:
<style type="text/css">
div.something {
width: 200px;
background-color: yellow;
}
</style>
<script type="text/javascript">
for (var i = 0; i < 5; i++) {
document.write("<div class='something'>text</div>");
// Or use the createElement/appendChild approach from above,
// where you'd need to set the div.className property as "something"
}
</script>
You need to add the element to the DOM to be able to access it later.
for(var i=0;i<5;i++)
{
//I'm not sure if you are just trying to make these changes each iteration
//or create a new element each time. If you are trying to create a new element
//each time. I'd def consider going a diff route i.e. use classes.
var b;
if( i==0 ){
b = document.createElement("DIV");
b.id = "blah";}
else{
b = document.getElementById("blah");}
b.style.width ="200px";
b.style.backgroundColor="yellow";
}

Categories

Resources