Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery element creation removes witdh and height when style attribute is ordered after width or height

After a very long search i have found this strange behaviour:

See fiddle: https://jsfiddle.net/723xhcrf/

When you create an element with params the width and height (maybe more) are added to the style argument like so:

$('<div>', {'width': '50px', 'height': '50px'});

Gives

<div style="width: 50px; height: 50px;">

But when you already have a style something strange happens based on the order of the keys of the params object.

$('<div>', {'width': '50px', 'style': 'background-color:blue;', 'height': '50px'})

gives

<div style="background-color: blue; height: 50px;">

And

$('<div>', {'height': '50px', 'style': 'background-color:blue;', 'width': '50px'})

gives

<div style="background-color: blue; width: 50px;">

What you see here is that the first width or height (maybe more) are overwritten by the style attribute that comes after it. I expect that both width and height in both cases are appended to the style attribute.

So my solution is to have a function that orders the params so that the style param is always the first key in the params object.

Does anyone know if this behavior is wanted or is this a bug in the jquery creation of dom elements?

like image 780
Encrypted Avatar asked Nov 14 '19 14:11

Encrypted


1 Answers

The object you pass as the second parameter is not simply a set of attributes for the new element. They're more like implicit calls to jQuery methods. Only when the property name is not a jQuery method is it treated like a simple attribute.

Thus,

$("<div/>", { width: "100px" })

is effectively like

let div = $("<div/">");
div.width("100px");

So when you also add a "style" value, that won't be treated as a method call. Because of the way object property name ordering works, if that comes after your "width" property, it will overwrite the "style" value that the "width" implicit call established.

Really, the right thing to do to control styles is to use a "css" property:

$("<div/>", { css: { height: "50px", width: "50px", backgroundColor: "red" } })

You can also do things like set the content:

$("<div/>", {
  text: "Hello World",
  id: "some-id",
  css: {
    height: "50px",
    width: "50px",
    backgroundColor: "red"
  }
})
like image 93
Pointy Avatar answered Nov 14 '22 23:11

Pointy