1
$('#test-list').append($(document.createElement("li")).attr({id: data.msg}));
$('#'+data.msg).append($(document.createElement("img")).attr({src: "kep.php?kep=upload/"+data.msg+"&w=180;&h=150;"}));

Does not work, because of the $('#'+data.msg). param. I don't know how to fix it. I want to make a sub-element to the #test-list and name it to the value of data.msg variable.

2
  • 1
    What is the value of data.msg and what exactly is not working? Any error messages? Commented Feb 15, 2010 at 20:26
  • 2
    Does data.msg change over time? E.g. is this in a loop structure? Commented Feb 15, 2010 at 20:26

5 Answers 5

2

You could chain this entire task:

  $("<li>")
    .appendTo("#test-list")
    .attr("id", data.msg)
    .append("<img>")
      .find("img:first")
      .attr("src", "kep.php?kep=upload/" + data.msg + "&w=180;&h=150;");

Which produces the following:

<li id="foo">
  <img src="kep.php?kep=upload/foo&amp;w=180;&amp;h=150;">
</li>

Where "foo" was the value of data.msg.

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

Comments

2

You are to be mixing DOM calls and jQuery in an odd way. I'd suggest doing it all with jQuery. The chain of elements is somewhat mixed up in terms of what you are appending to, and what you are specifying attributes for. You can specify the id, etc. directly in the creation of an element.

This should work:

$('#test-list').append($("<li id='"+data.msg+"'><img src='kep.php?kep=upload/"+data.msg+"&w=180;&h=150'></li>")

Comments

2

You can append the image as you create the <li>.

For example:

$('#test-list').append(
    $('<li><img src="kep.php?kep=upload/' + data.msg + '&w=180;&h=150" /></li>')
        .attr('id', data.msg)
    );

Comments

2

Try this out

var img = $("<img>").attr({src: "kep.php?kep=upload/"+data.msg+"&w=180;&h=150;"});
$("<li>").attr({id: data.msg}).append(img).appendTo('#test-list');

If you are using jQuery 1.4.x you can do:

var img = $("<img>",{src: "kep.php?kep=upload/"+data.msg+"&w=180;&h=150;"});
$("<li>",{id: data.msg}).append(img).appendTo('#test-list');

Comments

0

If I had to guess, I'd say that your data.msg has a value that isn't allowed as an ID for selector purposes (generally starting with [-a-zA-Z] and containing [_-\da-zA-Z]. If your image name (data.msg) begins with, or is a number, I'd suggest adding a prefix to the id.

In either case, you can do this in a single statement...

$("<li/>")
  .attr("id", data.msg)
  .append(
    $("<img/>")
      .attr("src", "kep.php?kep=upload/"+data.msg+"&w=180;&h=150")
  )
  .appendTo("#test-list");

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.