jconboy
jconboy

Reputation: 25

How to use div class style elements in node.style?

I am trying to incorporate css styles associated with particular div class names using node.style. I can get the styles to work individually but I am trying to implement multiple styles that span within one another using the div classes mentioned. I am wondering if there is a way of doing this using an easier method or can it be done at all?

var node = document.createElement("wall-post");  
var image = new Image();
image.src = obj.picture;
node.appendChild(image);
node.style=' display: inline-block;margin: 15px;margin-top: 30px; border-radius: px;overflow-y: hidden;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);float:left;';
document.body.appendChild(node);

Upvotes: 0

Views: 1006

Answers (3)

Quentin
Quentin

Reputation: 944150

The style property is related to the style attribute which accepts, as its value, the body of a CSS rule-set. It associates those rules with the particular element.

Selectors, including class selectors, appear outside the rule-set's body and cannot be included in a style attribute. (It doesn't make sense to do so anyway, the style attribute is associated with a specific element, so there is no point is selecting a different one from that context).

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075169

The style property on an element isn't a string, it's an object with properties for the styles. You set them individually.

node.style.display = 'inline-block';
node.style.margin = '15px';
node.style.marginTop = '30px';
node.style.borderRadius = /*?? Your question just has 'px' */;
node.style.overflowY = 'hidden';
node.style.boxShadow = '0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)';
node.style.float = 'left';

Note that you use the camelCase version (well, or node.style["margin-top"] = "...").

Alternately, if you want to completely replace the style, you can do that by using setAttribute to replace the style entirely:

node.setAttribute('style', ' display: inline-block;margin: 15px;margin-top: 30px; border-radius: px;overflow-y: hidden;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);float:left;');

All of that aside: In general, supplying style information in JavaScript code isn't a great pattern to follow. Create a descriptive class, then use that class on the element.

Upvotes: 2

Kootsj
Kootsj

Reputation: 431

You can also use node.className = "yourclass" and use css to define the styling of that class

.yourclass {
   display: inline-block;
   margin: 15px;
   margin-top: 30px; 
   border-radius: px;
   overflow-y: hidden;
   box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
   float:left;
}

Upvotes: 1

Related Questions