0

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>

4 Answers 4

1

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:

Sign up to request clarification or add additional context in comments.

Comments

1

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" }
});

Comments

1

.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"
});

Comments

0
$('.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'});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.