Search code examples
jquerypathappenddouble-quotes

How to write an img element with several double quotation marks when using "append"


I am trying to use "append" to add an img element on my html. But the img tag includes several double quotation marks. Is this a right way to use "append"? Or is there something wrong? Thank you for taking your time.

$($(".item .label")[0]).append(" <img src="images/king.png" alt="king"> ");

Solution

  • JS uses both ' and " to delimit strings. Therefore, you can alternate to avoid having to escape quotes within a string.

    You also don't need to double-wrap the jQuery object as you can use eq() to get the jQuery object by index instead of the Element object. Try this:

    $(".item .label").eq(i).append('<img src="images/king.png" alt="king" />');
    

    Alternatively (now that you edited the i to a fixed 0 value), you can just use the :first selector:

    $(".item .label:first").append('<img src="images/king.png" alt="king" />');