Reputation: 1
I'm trying to add css properties to an image that is set to a variable:
<script>
var img = '<img src="../common/img/check-mark.png">';
var imgCheck = img.css({'border':'1px solid red'});
$(function(){
$('.content li').before(imgCheck);
});
</script>
The image shows up without the css properties:
<script>
var img = '<img src="../common/img/check-mark.png">';
$(function(){
$('.content li').before(img);
});
</script>
If I add the css properties after the .before, it applies the css to the whole li.
<script>
var img = '<img src="../common/img/check-mark.png">';
$(function(){
$('.content li').before(img).css({'border':'1px solid red'});
});
</script>
Upvotes: 0
Views: 40
Reputation: 2500
.before()
returns the element(s) being operated on, not the element you inserted.
Reverse the operation like this:
$(img).insertBefore('.content li').css({'border':'1px solid red'});
or create it like this:
$("<img>", {
src: "../common/img/check-mark.png",
css: {border:'1px solid red'},
insertBefore: ".content li"
});
Upvotes: 1
Reputation: 1175
$('.content li').before(img).css({'border':'1px solid red'});
Here you are adding the CSS to $('.content li')
Add it to the img handle: $(img).css({'border':'1px solid red'});
Upvotes: 0
Reputation: 413996
You don't have an <img>
in a variable; you have the HTML code for an image. You can do what you're trying to do like this:
var img = $("<img/>", {
src: "../common/img/check-mark.png",
css: { border: "1px solid red" }
});
Upvotes: 1
Reputation: 253486
The problem is that you create a string of HTML, not a jQuery object containing an <img>
element:
var img = '<img src="../common/img/check-mark.png">';
And then try to use the CSS method on that string, which can't work, as strings don't have a css()
method; instead you'd first need to create a jQuery object (using that string of HTML):
$(img).css({'border' : '1px solid red'});
var img = '<img src="http://placekitten.com/g/250/250/" />';
$(img).css({'border' : '1px solid red'}).appendTo('body');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
References:
Upvotes: 1