I’m learning jQuery and i’m essentially wondering if it’s possible to use variables as selectors, like this:
let vbox = $("body").append("<div id='box'></div>");
vbox.css({
'width': '200px',
'height':'300px',
'background-color':'hsl(0, 0%, 10%)',
'border-radius':'10px',
'position':'absolute',
'color':'white',
'text-align':'center'
});
when I do this, the css code seems to apply to the whole document. I’m wondering if there’s anything wrong with this/if it just won’t work like that.
I figured out how to do it both of these ways:
var vbox = $("<div id='box'></div>")
$("body").append(vbox)
vbox.css({
width:'200px',
height:'300px',
background:'hsl(0, 0%, 10%)',
borderRadius:'10px',
position:'absolute',
color:'white',
textAlign:'center'
});
$("body").append("<div id='box'></div>");
var bx = $('#box')
bx.css({
width:'200px',
height:'300px',
background:'hsl(0, 0%, 10%)',
borderRadius:'10px',
position:'absolute',
color:'white',
textAlign:'center'
});
I’m just wondering what’s different about the first way and why it doesn’t work.
2
Answers
It’s different because the variables reference different elements.
In this case:
The
vbox
variable is a reference to (a jQuery wrapper for) the<body>
element. So when you apply CSS styling tovbox
, you apply it to the<body>
element.In these cases:
These variables are references to (jQuery wrappers for)
<div>
elements. So when you apply CSS to them you are applying it to those<div>
elements.Both versions "work", they’re just applying CSS to different elements.
As an aside… These aren’t "variables as selectors". The selectors are the strings you pass to the
$()
function. You’re simply storing the results of your functions in variables, as you likely would with any function that returns a result.Please accept the other answer. This is just to provide more details on some options using your generated HTML. Note the point of this is how to hit the DOM one time not multiple times. I added some in-line comments.