I have a javascript variable with the following value:
var style ="border-left:12px solid;border-color:red;position:relative;"
How can I apply it to a div like below:
<div class='my-div'></div>
I tried:
$('.my-div').css({style});
but failed spectacularly :(
var style = {
borderLeft:'12px solid',
borderColor:'red',
position:'relative'
}
The object should look like this. The CSS method takes in an object param. Doing a style string concat will work, but it's ugly.
Or use a class and be simple.
$('.my-div').css(style); //append style object to jQuery object
Note that using this object notation can also be beneficial because the properties can have logic in them, say for animations, or changing value dependencies.
Related
I have two DOM elements, A and B, and want to get all style classes from A, and append them to B.
I understand that I can append new classes to element, without wiping existing ones, this way:
B.classList.add("cls1", "cls2", "cls3");
or this way:
var clsa = ["cls1", "cls2", "cls3"];
B.classList.add(...clsa);
Now, my question is, how can I get a list of classes in A, in the form of clsa array?
I can do this by using A.className property, then splitting it into an array.
Or I can simply append A.className to the B.className, as easily as:
B.className += A.className;
Or I can iterate components of A.classList object, 0: ... N:.
The second one looks most natural. However, there's this feeling that the classList, not the className, is the preferred "home" for style classes of an object. Is that right?
And if so, is there any elegant and clear way to do so, without resorting to using className?
Maybe something like:
B.classList.add(...A.classList.all);
Unobvious, but appears to work in Chrome:
B.classList.add(...A.classList);
You can first try to cast classList to an array like it is answered in Why doesn't .includes() work with .classList? , and then append using spread operator.
B.classList.add([...A.classList]);
I'm using om as a clojurescript react interface.
One question, which I guess relates to both om and react:
Inside my html body I have a div of the id "app", which is used for om/react as a render target.
What would be a prefered way to change attributes outside of this element. more concretely I need to set some stylesheets to the body.
Now, more clojure specific:
How do you set multiple key-value pairs to a javascript object. (e.g. document.body.style)
I'm using this:
(doseq [[k v] {"backgroundColor" "red" "overflow" "hidden" ...}]
(aset js/document.body.style k v))
There was a nice way to do so with underscore.js:
_.extend(document.body.style, {"backgroundColor": "red" "overflow": "hidden"})
Well, but this was the question here. Maybe it's not really needed because there is a special om/react way to go.
A nicer way to do this is simply set the body style with a javascript object containing all key-value pairs:
(set! (.. js/document -body -style) #js {:backgroundColor "red" :overflow "hidden"})
The solution provided by Naomi is great, but it uses the bad practice of inline css. Instead of setting the actual css styles in code, I would set a class to the desired html object, and in the styles sheets define the css properties of that class.
For example:
(set! (.. js/document -body -className) "my-class")
I would like to add new properties to DynatreeNode class. For example in methods OnSelect I want to use node.myproperty. node.myproperty value is calculated from some DOM element. Is there a way to do this? I tried using jQuery extend, but it does'nt seem to be possible.
this is JavaScript, so you can create a new attribute virtually everywhere, simply by assigning it ;-)
For Dynatree, the recommended place would be the node.data object, e.g.
node.data.foo = "bar";
then access it:
onSelect(node){
if(node.data.foo !== undefined){
alert(node.data.foo);
}
}
I am wondering if I could use query and javascript together so I could select an element by class with the javascript and then use javascript to work on that element. Sorry if that didn't make sense. Here is an example:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
Would that work, if not how do I get an element by class using regular javascript. Thanks!
EDIT:I know JQUERY is JavaScript but I was wondering if I could mix jquery selectors and javascript 'controller'-for a loss of a better word
To answer your question as asked, there are several ways to take a jQuery object, i.e., what is returned by $('some selector'), and get a reference to the underlying DOM element(s).
You can access the individual DOM elements like array elements:
// update the src of the first matching element:
$(".nav_flag")[0].src = "images/flags/"+userCountryLower+".gif";
// if you're going to access more than one you should cache the jQuery object in
// a variable, not keep selecting the same thing via the $() function:
var navFlgEls = $(".nav_flag");
for (var i = 0; i < navFlgEls.length; i++) { ... }
But you wouldn't manually loop through the elements when you can use jQuery's .each() method, noting that within the callback function you provide this will be set to the current DOM element:
$(".nav_flag").each(function() {
this.src = "images/flags/"+userCountryLower+".gif";
});
However, jQuery provides a way to set attributes with one line of code:
$(".nav_flag").attr("src", "images/flags/"+userCountryLower+".gif");
To answer the second part of your question, doing the same thing without jQuery, you can use .getElementsByClassname() or .querySelectorAll() if you don't care about supporting older browsers.
jQuery IS Javascript. You can mix and match them together. But you better know what you're doing.
In this case, you probably want to use .attr function to set value of attribute.
Use .attr() in jQuery, rather than mix the two here.
$('.nav_flag').attr('src', "images/flags/"+userCountryLower+".gif");
In many instances, it is fine to mix jQuery with plain JavaScript, but if you have already included the jQuery library, you might as well make use of it. Unless, that is, you have an operation which in jQuery would be more computationally expensive than the same operation in plain JavaScript.
You can do it with jQuery too:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
keep in mind that jQuery is simply a library built upon javascript.
for any jQuery object, selecting its elements by subscription will return the corresponding dom element.
e.g.
$('#foo')[0] // is equivalent to document.getElementById('foo');
You need to add an index to the jQuery object to get the native Javascript object. Change:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
To:
$('.nav_flag')[0].src = "images/flags/"+userCountryLower+".gif";
To get elements by class name in Javascript you can use:
document.getElementsByClassName( 'nav_flag' )[0].src = "images/flags/"+userCountryLower+".gif";
To answer your question, you could use .toArray() to convert the jQuery object into an array of standard DOM elements. Then either get the first element or loop through the array to set all the elements with the class.
However, you could do this easier with pure jquery with attr or prop depending on the version:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
Or use pure javascript:
if (navFlagElements = document.getElementsByClassName("nav_flag") && navFlagElements.length > 0) {
navFlagElements[0].src = "images/flags/"+userCountryLower+".gif"
}
Is there a way to assign attributes in a more compact manner
I dont really want to use setAttribute as it seems to be buggy in ie8
This list is for all attributes so its quite long
else if(a=="textalign")
{
e.style.textAlign="";
e.align=v
}
if(a=="textalign")
{
e.style.textAlign="";
e.align=v
}
I don't know why you are trying to set alignment via an HTML attribute rather than just using the CSS... this is much less reliable as there are many elements which have no align attribute. HTML align is also deprecated and should be avoided in general.
You don't say what the “other attributes” are that you might want to set. If you are talking specifically about HTML attribute properties it's easy to set them by a name in a string:
e[a]= v;
But then you need a to be the HTML attribute property name, which would be ‘align’ not ‘textalign’. It wouldn't do anything special to try to workaround CSS overrides like textAlign, because there is no automated way to do that, and the interaction between the deprecated HTML styling attributes and CSS is ill-defined. Stick to attributes or CSS (CSS is highly preferable); don't use both.
If you are talking about setting any CSS style property, as I might guess from the name being ‘textalign’, that's done similarly:
e.style[a]= v;
But then, again, you'd want to be using the exact style property name ‘textAlign’ not ‘textalign’.
If you want to set CSS style properties by their CSS name, like ‘text-align’, you could transform that to the DOM name automatically:
// convert foo-bar-baz to fooBarBaz
//
var doma= a.replace(/-([a-z])/g, function(m, g) {
return g.toUpperCase();
});
e.style[a]= v;
If you really do need to use case-lossy names like ‘textalign’ you'd have to use a lookup of all property names you wanted to use to get the case back:
var propernames= ['textAlign', 'borderColor', 'paddingTop']; // etc
for (var i= propernames.length; i-->0;)
if (propernames[i].toLowerCase()===a)
a= propernames[i];
e.style[a]= v;
Forget setAttribute. It has nothing to do with style properties (it's a bug in IE6-7 that it even works on styles there), and you shouldn't use it on elements either for HTML documents, as there are other IE6-7 bugs to contend with there. Stick to the ‘DOM Level 2 HTML’ direct property access stuff, which is more reliable and easier to read.
Use a class instead of giving all the attribute values.
.testClass
{
// set all attribute values here
}
e.className = "test";
See
element.className
Use some framework such as JQuery, it takes care of all of your browser incompatibility issues. In JQuery you use the .css('attributeName', 'value')method.
jQuery would make that easy with .attr({attr1: val, attr2: val}) etc. It would also shield you from many cross-browser compatibility bugs.