Can an element's CSS class be set via JavaScript? - javascript

I want to do this:
e.className = t;
Where t is the name of a style I have defined in a stylesheet.

If e is a reference to a DOM element and you have a class like this: .t {color:green;} then you want reference the class name as a string:
e.className = 't';

Yes, that works (with the class name as a string, as jonah mentioned). Also, you can set style attributes directly on an object, using the DOM Level 2 Style interface. e.g.,
button.style.fontFamily = "Verdana, Arial, sans-serif";
where button is (presumably) a button object. :-)

Not only that works, but it's even a best practice.
You definitively want to separate the data format (xHTML) from the design (CSS) and the behaviour (javascript).
So it's far better to just add and remove classes in JS according to event while the esthetic concerns are delegated to css styles.
E.G : Coloring an error message in red.
CSS
.error
{
color: red;
}
JS
var error=document.getElementById('error');
error.className='error';
N.B :
This snippet is just an example. In real life you would use js just for that.
document.getElementById is not always interoperable. Better to use a JS framework to handle that. I personally use JQuery.

Here is the example that add and remove the class using jQuery.
// js
$("p:first").addClass("t");
$("p:first").removeClass("t");
// css
.t {
backgound: red
}

document.getElementById('id').className = 't'

Related

add a change color in js

I am trying to add a function into common.js that will change the background color of a button. Is this possible? thanks guys.
$('#api_search').style.backgroundColor('#e4e4e4');
$('#api_search').css("background","#e4e4e4");
or
$('#api_search').attr("style","background:#e4e4e4");
If you're trying to do this with Javascript, you could do something like the following:
document.getElementById("api_search").addEventListener("click", function(e) {
e.target.style.backgroundColor = "red";
});
Check this out for clarity:
https://jsfiddle.net/9p3f9yjw/2/
You're using a jquery selector which means you'll have different functions/properties available to you than accessing DOM elements in vanilla javascript. Using this approach, you can set multiple css declarations in one function.
If you wanted to change other styling properties, you would just add them to the object passed as the argument to css.
{backgroundColor:'#e4e4e4', color: '#fff', ...}
So you could use .css as follows:
$('#api_search').click(function() {
$(this).css({backgroundColor:'#e4e4e4'})
});
try it here with a button
see jquery css() documentation here

apply css style to multiple nodes having the same css class using dojo

I have been applying or changing the style for a CSS class in the javascript script, having a dojo f/w, like this,
this.sidePanel = query(".sidePanel", document.body())[0];
domStyle.set(this.sidePanel, {
height: "25%",
top: "334px"
});
This has worked fine but now I am having multiple nodes with similar CSS class. I wish to apply the new CSS style to the class and thereby all the nodes having the same class.
Is there some function in dojo which allows change in style to the CSS class directly without having to query for the node? Something like,
dojo.css.applyNewStyle('className', {'cssProperty': 'newValue'});
The dojo/query function returns a nodelist which you can operate on. If you also require the module dojo/NodeList-dom which extends dojo/query, you can do something like:
require(['dojo/query','dojo/NodeList-dom','dojo/domReady!'],function(query){
query('.red').style('background-color','black');
});
I made a quick jsfiddle to demonstrate this. The dojo reference guide has a list of additional methods you can call on a nodelist, including adding a css class, which might be what you want (if your new css values are static rather than dynamic).
And if you don't want to include the dojo/NodeList-dom module, you can still do this :
query(".sidePanel").forEach(function(node){ domStyle.set(node, { height: "25%", top: "334px" })});
...but yeah, dojo/NodeList-dom is more concise :-)
Yes there seems to be a way, but you don't need to use dojo. Check out this other post:
Changing CSS Values with Javascript

Values of "class" attribute implicitely expand for certain markup elements

I'm experimenting with a third party library written on top of jQuery.
I noticed, for a number of their widgets, that when your source says, for example,
<div id="myWidgetInst" class="their-widget-class-0" ... </div>
Firebug shows that the resulting DOM element reads:
<div id="myWidgetInst" class="their-widget-class-0 their-widget-class-1 ..." ... </div>
How do they do it? Many thanks.
it's probably jquery !
there's probably a function running adding classes to the elements
Not sure I fully understand your question but when looking at the "regular" source of the website, this source doesn't show any modifications to the DOM that happened due to javascript modifications. Firebug does show these updates.
using jQuery, you can add/remove classes simply by using .addClass("className") or .removeClass("className") function on the element you want to modify
They would add classes to the element with jQuery. For example, if the plugin's purpose was to hide all elements on the page (innovative and highly practical, I know), they could use the following:
$(document).ready(function() {
$("*").addClass("my-widget-made-your-element-invisible");
});
With the CSS:
.my-widget-made-your-element-invisible { display: none; }
The methods in which you can manipulate the class attribute in jQuery include the following:
$("#elem").addClass("a"); // adds the class "a" to elem
$("#elem").removeClass("a"); // removes the class "a" from elem
$("#elem").attr("class", "a"); // gives elem a complete class of "a"
$("#elem").attr("class", ""); // removes all classes from attribute

how to avoid looking css property using jquery or javascript

There is some content in html page and one of div style for that is like below:
.class1{
property1:value1;
property2:value2;
property3:value3;
property4:value4;
}
I want to avoid applying css property property1 into concerned content and rest property property2, property3, property4 are welcomed.
I want to avoid applying property1 and don't want to change the css file.
Also I don't want to use as below:
$('.class1').css('property1','some different value');
I just want to avoid property1 using code.
Please tell me how I done using jquery or js.
----------------------Edited------------------------
I don't want to generate any inline css on run time.
I am looking ui code some thing like as below:
$('.ui-resizable').css('position').disable()
There is not function avaialbe to do that , one way to achieve this is
$('.class1').css('property1','');
Just set an inline style on the element that negates the property or makes it what you want. No jQuery necessary. Inline styles will always override inherited styles.
<div class="class1" style="margin:whatever"></div>
Make another class "class2" with css and use
/* CSS */
.class2{
property1:value1;
}
//JQuery
$('div').removeClass('class1').addClass('class2');
Preserve the value of property1 as:
var p1 = $('.class1').css('property1');
Now apply changes to the class as necessary.
Finally, restore the value of property1 as:
$('.class1').css('property1',p1);

Change CSS based on Javascript?

I'm wondering how would I change a CSS element in javascript..e.g if a user clicks a button it changed the background from white to black
Every DOM element has a style property that allows manipulation of CSS properties on that object as if you were mucking with it's style attribute.
The below will toggle the color of the document body but is equally applicable to other HTML elements.
<button onclick="document.body.style.background = (toggle = !toggle) ? 'black' : 'white'">Toggle Background</button>
As TheBuzzSaw points out, you need to camel case them.
So the JS property is backgroundColor instead of background-color.
The rule is basically
var javascriptProperty = cssStyleProperty.replace(
/-([a-z])/g,
function (_, followingLetter) { return followingLetter.toUpperCase(); });
but there are a few exceptions : since float is a keyword in many languages, the CSS style property is cssFloat. The exceptions are explained under JavaScript syntax in the w3schools pages : http://www.w3schools.com/css/pr_class_float.asp
JavaScript syntax: object.style.cssFloat="left"
There are many properties/attributes that can be manipulated directly from JavaScript. You just need to know their names. They are usually strange camel case equivalents of the CSS property names. A quick Google search reveals lots of places to learn about this.
http://www.comptechdoc.org/independent/web/cgi/javamanual/javastyle.html
load new image with black color on click event of the button
If you don't mind using a framework, have a look at jQuery, especially this:
http://api.jquery.com/css/
Framework agnostic script:
http://jsfiddle.net/chprpipr/kWRRN/1/

Categories

Resources