Please take a look at my small script that checks if a style is defined on an element already .
HTML :
<div id="la" style="width: 100px;height: 100px;background: #eee;">
</div>
And the JS :
var _str = document.getElementById('la');
/*A object literal that contains some pretty random set of css definitions */
var str_elem = {
'padding' : '40px',
'width' : '100px'
}
/*we are using the for loop to check if the properties defined in our obj literal are actually present in the element style definition.*/
for(var name in str_elem){
if (_str.style[name] == ' ') {
console.log('not present' + ' ' + str_elem[name] );
}
}
My question is about the if condition and the syntax inside it. Usually when we want to get an elements style we use the following syntax:
elementname.style.propertyname
But why, when checking if the element has a property, are we using the following syntax:
elementname.style['padding']
??
And why does this syntax throw an error :
elementname.style.propertyname
My script works fine, my question is about the JS syntax.
EDIT:: to condense my difficulty , let me rephrase my question :
if in the if condition that i have i use the following syntax :
_str.style.[name] (note the dot after style) , instead of what i currently have _str.style[name] , Why is an error thrown . ?
Because you want to check that the value of the name variable is present as a style in your element. If you write _str.style.name, you would be checking the definition of the style called name. Brackets allows you to dynamically check the property, or to check property with hyphens, for example _str.style['my-dashed-property']
By the way, considering that the style property is not present because it equals a blank string is weird.
The syntax obj.[name] does not work because the dot operator is for accessing properties via fixed keys, hence you look for a property called [name] and that is not allowed
Ok, I see the confusion you have.
Before everything else, read this article.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
In JavaScript, you can access the properties of any variable in two ways.
1) obj.propertyName
2) obj['propertyName']
Now, coming to your question:
_str.style.[name] // Error is thrown because it is syntactically wrong to be accessing the object properties like this.
Just console.log your _str.style and observe that it is an object.
So,
_str.style.[name] // Does not make any sense, syntax wise. Hence the SyntaxError.
And since, you are trying to access the object properties dynamically inside for loop, you write like this:
_str.style[name] // Here name is a variable whose value is dynamically set during each iteration of the loop.
Related
object.style.flex-direction="column";
I tried to achieve this in a JavaScript function, but I don't know if it's possible to replace the property name with variable name.
Can I use a variable name instead of a property name in the above expression, i.e.
object.style.applyFlexProp = "column";
where applyFlexProp will be assigned at runtime? It can be either, flex-direction, justify-content, align-content, etc.
Replace object.style.flex-direction="column"; with object.style.flexDirection="column";
When using JavaScript, replace a CSS some-thing with camelcase someThing.
This is because - is not a valid identifier character.
To apply the key dynamically, use the [] notation.
object.style["flexDirection"] = "column";
I am learning javascript myself. There is a confusion with some javascript,
price = 14;
name = "Mary";
apples:5; //This line executing without error
"orranges":6; //This line getting error
alert(name);
Those both lines can be used into a json object without any error. But when I am using those lines outside of json object, 2nd line ("orranges":6;) is getting error. Why is that ? And why is not giving error for the first line (apples:5;), is there any way that I can use it outside of json object ?
: isn't an operator, it forms part of label syntax.
See MDN
label : statement
labelAny JavaScript identifier that is not a reserved word.
apples is an identifier.
"orranges" is a string literal.
is there any way that I can use it outside of json object ?
You seem to be confusing JSON with object literal syntax.
You can't use a : as the character that separates a property name from a value in an object when you aren't in the process of defining an object.
I am using this script to make a style object of all the inherited, etc. styles.
var style = css($(this));
alert (style.width);
alert (style.text-align);
With the following, the first alert will work fine, but the second one doesn't... it's interpreting the - as a minus I assume. The debugger says 'uncaught reference error'. I can't put quotes around it, though, because it isn't a string. So how do I use this object property?
Look at the comments. You will see that for CSS properties, the key notation is not compatible with a number of properties. Using the camel case key notation therefore is the current way:
obj.style-attr // would become
obj["styleAttr"]
Use key notation rather than dot
style["text-align"]
All arrays in JavaScript are objects and all objects are just associative arrays. This means you can refer to a place in an object just as you would refer to a key in an array.
arr[0]
or the object
obj["method"] == obj.method
A couple things to remember when accessing properties this way:
they are evaluated so use strings unless you are doing something with a counter or using dynamic method names.
This means obj[method] would give you an undefined error while obj["method"] would not
You must use this notation if you are using characters that are not allowed in JavaScript variables.
This regex pretty much sums it up:
[a-zA-Z_$][0-9a-zA-Z_$]*
The answer to the original question is: place the property name in quotes and use array style indexing:
obj['property-with-hyphens'];
Several have pointed out that the property you are interested in is a CSS property. CSS properties that have hyphens are automatically converted to camel casing. In that case you must use the camel cased name like:
style.textAlign;
However this solution only works for CSS properties. For example,
obj['a-b'] = 2;
alert(obj.aB); // undefined
alert(obj['a-b']); // 2
CSS properties with a - are represented in camelCase in JavaScript objects. That would be:
alert( style.textAlign );
You could also use a bracket notation to use the string:
alert( style['text-align'] );
Property names may only contain characters, numbers, the well known $ sign and the _ (thanks to pimvdb).
Use brackets:
var notTheFlippingStyleObject = {
'a-b': 1
};
console.log(notTheFlippingStyleObject["a-b"] === 1); // true
More information on objects: MDN
NOTE: If you are accessing the style object, CSSStyleDeclaration, you must use camelCase to access it from JavaScript. More information is here.
alert(style.textAlign)
or
alert(style["textAlign"]);
To directly answer the question: style['text-align'] is how you would reference a property with a hyphen in it. But style.textAlign (or style['textAlign']) is what should be used in this case.
Hyphenated style properties are referenced via camelCase in JavaScript, so use style.textAlign.
To solve your problem: The CSS properties with hyphens in them are represented by JavaScript properties in camelCase to avoid this problem. You want: style.textAlign.
To answer the question: Use square bracket notation: obj.prop is the same as obj["prop"] so you can access property names using strings and use characters that are forbidden in identifiers.
I think in the case of CSS styles they get changed to camelCase in JavaScript, so test-align becomes textAlign.
In the general case, where you want to access a property that contains non-standard characters, you use array-style: ['text-align']
The object property names are not one-to-one matches for the CSS names.
At first, I wondered why the solution didn't work on my end:
api['data-sitekey'] // Returns undefined
...later on I figured out that accessing data attributes was different:
It should be like this:
var api = document.getElementById("some-api");
api.dataset.sitekey
I'm working on a JS class that creates several elements and attaches them to the DOM, and I would like for the class to also set the style attribute properties of those elements. I have a function already that does this for other attributes:
function setAttrs(el, attrValArray){
for(var i=0; i<attrValArray.length;i++){
el.setAttribute(attrValArray[i][0],attrValArray[i][1]);
}
}
The attrValArray input is a 2D array that would look something like
attrValArray = [["class","container"],["id","cc1]];
So what I want is to be able to create a similar array for style property pairs such as:
propValArray = [["display","inline-block"],["position","relative"]];
Which I would then pass to a similar setStyles function.
I could use the same setAttribute method, but instead of looping over the array and setting attributes individually I would have to construct a long string and pass the whole thing as the second argument of setAttribute since I am actually setting many properties of only 1 attribute. But I'd like to avoid this because of the fact that it would override any existing inline styles (not that I use inline styles, but for the sake of principle).
The better option is to set the properties of style on the element. I.e.
el.style.<property-to-set> = "property value";
This does not overwrite anything other than the specific property being set. But I don't see any way to select the "property-to-set" using values from a list. Is there an appropriate way around this?
To be clear, I already know that I can simply assign the desired style attributes to the to-be-created element classes/ids, and was actually wondering if that is the technically correct thing to do based on "good practices" and whatnot. That is what I plan on doing if there is no satisfying alternative.
Also, as stated in the question, I'm strictly interested in a pure JS solution, no JQuery or any other such library/framework.
I don't see any way to select the "property-to-set" using values from a list.
Unless I'm misunderstanding the question, you would do it pretty much the exact same way:
function setStyles(el, cssArray){
for(var i=0; i<cssArray.length;i++){
el.style[cssArray[i][0]] = cssArray[i][1];
}
}
Remember with objects, you can access properties using dot notation object.property or bracket notation object['property']. When you use bracket notation, the text inside the brackets is evaluated, just like when looking up indexes in an array (arrays are really just special objects with number properties).
Alternatively, you could build one long string out of all the property/values pairs and use setAttribute or cssText:
function setStyles(el, cssArray){
let cssText = '';
for(var i=0; i<attrValArray.length;i++){
cssText += cssArray[i][0] + ':' + cssArray[i][1] + ';';
}
el.style.cssText = cssText;
// or el.setAttribute('style', cssText);
}
I have a ternary ahead of variable instantiations. The problem is, that this is an incorrect way to assign a variable for an attribute.
$partial = $data.cell_info_box === undefined ? job_box : cell_info_box
$rel = $($data.$partial).attr('rel');
$klass = $($data.$partial).attr("rel").match(/job/) == null ? 'task' : 'job';
How can I provide my ternary like demonstrated but create callable attributes with my initial ternary's product?
Based on your comment, what you want is $data[$partial]. This syntax is used when you want to get a value from an object without knowing the key name until runtime. You may also see this problem incorrectly solved through the use of eval but this is the correct way.