Reputation: 23500
I have something like the following jQuery code
buttons =
document.createElement('div');
$(buttons).addClass("overlay_buttons").css({
styles });
save =
document.createElement('input');
$(save).attr({ type: "button",
value: "Save"
}).css({width:'45%'});
undo =
document.createElement('input');
$(undo).attr({ type: "button",
value: "Start again"
}).css({width:'93%'});
//add elements to document
$(buttons).append(undo);
$(buttons).append(save);
$(buttons +'> input').css({
shared styles for buttons
});
The problem I have is that the shared styles for the buttons don't apply. I get no error messages. I've also tried using other jQuery methods to check it's not the css that's the problem, but nothing applied to $(buttons +'> input') works.
Does anyone have any idea why?
Upvotes: 0
Views: 633
Reputation: 488374
Your problem is here:
$(buttons +'> input').css({
shared styles for buttons
});
buttons
at that point is not a string, but a DOM element object. So when you try to append this object to the string > input
your selector ends up being something like "[object HTMLDivElement] > input", which is obviously not right.
This should work, as according to the children()
documentation it only selects the immediate children, replicating the behavior of the >
selector:
$(buttons).children('input').css({
shared styles for buttons
});
Or, if that doesn't, which it should, then you can try this, although I don't feel good about it:
$('> input', buttons).css({
shared styles for buttons
});
Also, I am not sure why you are individually creating the elements with createElement
. jQuery supports creating DOM elements on the fly. Using that, you can shorten this:
undo =
document.createElement('input');
$(undo).attr({ type: "button",
value: "Start again"
}).css({width:'93%'});
To this:
$('<input>').attr({ type: "button",
value: "Start again"
}).css({width:'93%'});
Upvotes: 4