Dylanthepiguy
Dylanthepiguy

Reputation: 1731

Strange Javascript/JQuery behaviour when creating a div element

    menuPaneToBe.title = document.createElement("div");
    $(menuPaneToBe).append(menuPaneToBe.title);
    console.log(1)
    console.log(menuPaneToBe.title)
    $(menuPaneToBe.title).addClass("menuTitle");
    console.log(2)
    $(menuPaneToBe.title).html("Title"); //Just placeholders, gets changed by circular-view
    console.log(3)

Console

1 MenuPane.js:12
[object HTMLDivElement] MenuPane.js:13
Uncaught Error: Syntax error, unrecognized expression: [object HTMLDivElement] jquery-1.11.0.min.js:2

Why is the title just [object HTMLDivElement] instead of being a proper object? and why can't I set the class? MenuPaneToBe is a custom tag that is set to display block.

<menu-pane id="menu"></menu-pane>

menu-pane {
    display: block;
    height: 100%;
    width: 30%;
    border-left: 1px solid black;
}

Upvotes: 0

Views: 170

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388406

It is an strange issue, if menuPaneToBe is referring to a dom element(not jQuery object) then the title property will refer to the element's title property which is a string value. At least in Google Chrome when you assign a value to title of an element, it converts it to a string object.

So when you say menuPaneToBe.title = document.createElement("div"), it assigns the string value [object HTMLDivElement] to menuPaneToBe.title, which is an invalid jQuery selector.

Then when you say $(menuPaneToBe.title) it will throw the said error.

Demo: Fiddle

Just change the property name from title to something else like title2

var menuPaneToBe = $('#menu')[0];
menuPaneToBe.title2 = document.createElement("div");
$(menuPaneToBe).append(menuPaneToBe.title2);
console.log(1)
console.log(menuPaneToBe.title2)
$(menuPaneToBe.title2).addClass("menuTitle");
console.log(2)
$(menuPaneToBe.title2).html("Title"); //Just placeholders, gets changed by circular-view
console.log(3)

Demo: Fiddle

Upvotes: 1

Related Questions