Why doesn't CSS properties work properly with Javascript? - javascript

So:
I just tried to use loops to add a background color and a border to each element in class .readtrue or .readfalse, but then somehow the last element, even though it changed class like the others, did not change the border or background color.
Then I tried to add something in Javascript that would just add <style> </style> element to <head> </head>, but according to a console error the <head> </head> element does not exist, although checking the information about the page this item exists.
Then I just tried to change the properties of these classes in a separate CSS file, but it had no effect.
That's why I'm here. I'm a Javascript beginner and have no idea how to change the background color so that the browser will say it's worth showing.
if (val.read === true) {
div.setAttribute('class', 'readtrue')
} else {
div.setAttribute('class', 'readfalse')
}
val is an object with the 'read' attribute and depending on whether 'read' is true or false, div class should change.

I am not sure how you are getting the variable div but a simple example for what you want to achieve is as follows.
I have commented the code, if you need more clarity, kindly comment on this answer.
function toggleBackgroundColors() {
// Fetch all the elements which has 'element' as a class
var spans = document.getElementsByClassName("element");
// Loop through all the fetched elements
for(var i =0 ; i < spans.length;i++) {
var element = spans[i]; // assign a single element
// Check if the element already has a 'bgColor' class
if(element.className.includes("bgColor","")) {
// If it does, simply remove it
element.className = element.className.replace("bgColor","");
}
else {
// If it does not, simply add it
element.className += " bgColor";
}
}
}
/* basic styling for the element */
.element {
width:20px;
height:20px;
display:inline-block;
border:1px solid #000;
background-color:blue;
}
/* color class you want to add */
.bgColor {
background-color:red;
}
<div>
<span class="element"></span>
<span class="element"></span>
<span class="element"></span>
<span class="element"></span>
<span class="element"></span>
</div>
<button onclick="toggleBackgroundColors()">toggle color</button>

I just tried to use loops to add a background color and a border to each element in class .readtrue or .readfalse, but then somehow the last element, even though it changed class like the others, did not change the border or background color.
It's possible you have another styling overriding your class's style on the last element. Bootstrap and css pseudo-classes like :hover are the usual culprits. Use your browser developer tools and append your class's style with !important, like so background-color: yourColor !important; to test it out.
You could also be adding both classes
Then I tried to add something in Javascript that would just add element to , but according to a console error the element does not exist, although checking the information about the page this item exists.
The correct way to query an element by tag name is document.querySelector("head") or $("head") in jQuery, but jQuery returns a jQuery Object so you dereference it by doing [0]
BUT
Using JavaScript to append a <style> element to the <head> section of your page is horrible practice. Please just add the styling through a reference to a style sheet on the actual HTML.

Related

How to style the active element using javascript [duplicate]

This question already has answers here:
Setting CSS pseudo-class rules from JavaScript
(12 answers)
Closed 6 years ago.
I can use CSS to style an element so that it changes appearance when active. For instance:
.test:active {
background-color: yellow;
}
But how do I do this in javascript if I want to apply it to a specific element, not by class? I can set the background color for the default state using:
document.getElementById("myid").style.backgroundColor = "yellow"
But I can't do this:
document.getElementById("myid").style.active.backgroundColor = "yellow"
I don't want the javascript to respond to the element being active or not - I want to do a static initialization in javascript that then makes a specific element have a different color when it is active.
If the element was guaranteed to have an id I could use javascript to append a style sheet rule which used the #id selector, but I don't have this guarantee. All I can be sure of is I will get a reference to an element and I need to style it so that it has a different color when active.
You could use event listeners with the specific element.
When defining element, try this. You can of course make it a button or whatever:
<!-- in this case, using 'this' will refer to the element at hand. this way the element is targeted even if it has no ID or class -->
<input onfocus="elemFocused(this)" onblur="elemBlurred(this)">
This makes it so that when you focus the element (make it active), it runs the focused function. When it blurs (you select a different input or something), it runs the blurred function. In javascript:
function elemFocused(element){
element.style.backgroundColor = 'yellow'; // sets BG color to yellow
}
function elemBlurred(element){
element.style.backgroundColor = 'initial';// sets BG color to default; you can change if needed
}
I'm not certain that you have programatic access to the ':active' style directly, but you do have access to the active event so you can replicate it with something like this:
In your CSS add a css class to handle your active state, something like:
.active{
background-color: red;
}
Then just add the class on that event:
document.getElementById("myid").onfocus = function(){
this.className += "active";
};
document.getElementById("myid").onblur = function(){
this.className = "/*replace this with the original classes*/";
};

Changing the Style Attributes in javascript use className

HTML
<h1>Changing the Style</h1>
<p>JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="openMe()">Open!</button>
<button type="button" onclick="closeMe()">Close!</button>
<p id="demo">Extra details...You can open and close this paragraph using the buttons above.</p>
CSS
.close {
display: none;
}
.open {
display: block;
}
button {
width:150px;
background-color: #00CCEE;
margin-left:15px;
font-size:120%;
}
#demo {
color:white;
background-color: #7F7F7F;
padding:10px;
font-size:120%
}
JAVASCRIPT
function closeMe(){
x=document.getElementById("demo");
x.className="close";
}
function openMe(){
x=document.getElementById("demo");
x.className="open";
}
Can I use Like x.IdName= "close"; In Javascript?
So far I know there are two ways to change style attributes using Javascript.
x = document.getElementById("demo");
directly eg.. (x.style.backgroundColor ="red";
by Class name eg.. (x.className="abc";)
for using class name we do use:
x = document.getElementById("demo");
x.className="abc";
My questions:
Can I use Id to change style attributes insted of useing className? if yes Please show.
Can I call "x" {x=document.getElementById("demo");} a variable?
There are three ways to modify the style of an element with JavaScript:
Modify the inline style. This is represented by the .style property on the element and the style attribute on the HTML tag.
Modify any feature of the element so that selectors on rulesets in the stylesheet start and or stop matching it. e.g. .foo { ... } would match elements that are members of the foo class, so if you modify the .className property to add or remove an element from that class, you will change the rules that apply to it. You can change other factors such as the id (not usually a logical idea), arbitrary attributes, or anything else that a selector exists for.
Modify the rulesets in the stylesheet itself.
You've already modified the style attribute of the element in your example.
x.style.backgroundColor= "red";
This is what modifying the style attribute is. The second example you edit the elements class name. I'm assuming what you mean is if you can apply styles to elements, using ids?
If that's the case, you can style elements by using the class selector which looks like this
.className {
/* Some styles */
}
Or with the id selector
#demo {
/* Other styles */
}
The two examples above either need to go into their own stylesheet, or inside the HTML in a <style></style> element.
document.getElementById selects element having certain ID. When You want to select elements by a classname, you can use i.e. document.querySelector('.your-class') to select nodes containing your-class className.
When You write
x = document.getElementById("demo");
x.style.backgroundColor ="red"
You are setting style using Id to select a node.
In the line x = document.getElementById("demo");x is the variable.
After running this line, the value of this variable is set to whatever function document.getElementById("demo"); returns. In this case, it's pointing to DOM element with Id attribute "demo".

Is it possible to get all global/inherit css classes applied to an element?

I need a javascript function that can get me all the CSS classes applied to an element.
We have function like getComputedStyle(element,"") and currentStyle(), FF and IE respectively.
But, these function only give me the CSS properties applied to the element, not the classes.
To make things more clear please see the following DOM structure.
<html>
<head>
<style>
.dd{
font-weight:bold;
}
.dd span{
border:solid 1px #ABABAB;
}
</style>
</head>
<body>
<div class='dd'>
<span id='span1'>Hi this is a example</span>
</div>
</body>
</html>
Now what the javascript should is if i get the element 'span1' it should give me all the classes that are applied to this element. Say the output should be giving me ".dd span and .dd"
document.getElementById('span1').className;
and you can use .parentNode to get various parent classes.
And, if you give the topmost parent a position style, you could use this:
var topmost = document.getElementById('span1').offsetParent;
for(var x = 0; x < topmost.childNodes.length;x++) {
alert(topmost.childNodes[x].className);
}
// Edit
It looks like you're trying to do a Firebug type of thing. A lot of users here on SO have tried the same. A good search might lead you to things you never dreamed of...muhahahaha....
As a continuation from Steve's answer, you can just loop through the parent nodes and list the class names for each parent node.
var listClasses = function(element){
while(element){
console.log(element.className);
element = element.parentNode;
}
}
To Use:
listClasses(target);

alter divs css with javascript

Can I change style of some div link. Here is what I mean
<div id="somediv">something/div>
Lets say I have css like this :
#somediv a{
color:#000;
}
Now for instance upon some action such as mouse click on any element I want to change somediv a link css to
#somediv a{
color:#00ffff;
}
I know how to select div, by using Document.get.elementById('somediv') Is it possible to select a by using above method or any other?
Thank you
DETAILS: Yes I know how to select it using jquery, or prototype .. I can't use any of those..
If you just want to apply a style to a particular element, it's very easy to do:
document.getElementById('whatever').style.color = '#f0f';
If you actually want to apply cascading styles (eg: #someDiv a), then it's not so easy (though it is definitely possible). I would suggest applying a new class to something, and having a pre-existing rule in your CSS.
CSS:
#someDiv a {
color: #000;
}
#someDiv.awesome a {
color: #f0f;
}
Javascript:
document.getElementById('someDiv').className = "awesome";
Yep, you can modify the actual CSS rules at runtime. See Totally Pwn CSS with Javascript for more details.
If you're using jQuery or YUI, there's some good info in question 1079237
document.getElementById ( 'somediv' ).children[0].style.color = 'new color';
assuming the A tag will be the first element inside your DIV
You could use CSS behaviors for this:
For instance:
#somediv a:hover
{
color:#0ff;
}
Otherwise, you may create a dedicated class (used when an element is click for example):
#onclickclass
{
color:#0ff;
}
Then in JavaScript, on onClick event, do:
document.getElementById('somediv').className = 'onclickclass';
And to change the style use
document.getElementById('somediv').className = 'your-css-class';
If you really want to select the anchor you would have to then traverse the document.getElementById('somediv').children array.
As others have suggested though the simpler answer would be to set the className attribute on your div and let the CSS style cascade onto the anchor tag.

How to change css properties of html elements using javascript or jquery

How can I change CSS from javascript.
I'm using jQuery-ui Dialog and I want to change the style of a DIV from javascript.
Thanks
Check out the jQuery documentation. If you want anything it will be there.
Anyhow, if you want to add styles to elements, you need to use the css function, which has a few variants.
$(selector).css(properties); // option 1
$(selector).css(name, value); // option 2
So if you have a DIV with ID of "mydiv" and you want to make the background red, you would do
$("div#mydiv").css({'background-color' : 'red'}); // option 1
$("div#mydiv").css('background-color','red'); // option 2
The first way is easier if you're setting multiple things at once.
If you want to check what a property is currently set to, you would use a variant of the 2nd option, just omit the value.
var color = $("div#mydiv").css('background-color');
Would make the var color be red if you already set it above, for example.
You can also add and remove classes, doing something like
$(selector).addClass(class_name);
$(selector).removeClass(class_name);
This answer works even without jQuery.
So you have something like this:
<style type="text/css">
.foo { color: Red; }
.bar { color: Blue; }
</style>
<div class="foo" id="redtext"> some red text here </div>
If you wish to change just some attributes, you can always find the element using
var div = document.getElementById('redtext');
function and then change the attached color style by
div.style.color = 'Green';
Making your red text appear in green instead.
If you want to change the class defined for the div to another style class, you can do:
div.className = 'bar';
making the div now use class bar, which makes your previously green text blue.
There are a couple of ways to manipulate elements styles using the jQuery framework. Take a look through the documentation related to CSS and changing attributes:
http://docs.jquery.com/Attributes/addClass#class
http://docs.jquery.com/CSS
Try this.This is jquery code.
$("myDiv").css({"color":"red","display":"block"})
If you are using vanila javacript,try this.
var myDiv = document,getElementById("myDiv");
myDiv.style.display = "block";
myDiv.style.color = "red";

Categories

Resources