Tool
Tool

Reputation: 12488

jquery: appending a [object Object] to a string

Jquery can't seem to turn the type of str2 into a string, no matter what i tried.

function parseXml(xml)
{
      $(xml).find("product").each(function()
      {

           var str1 = "div.timer";
           var **str2** = $(this).find("id");


           $("div.timer17").html(str1 + str2);
      });
}

Every time this function is ran, content of div.timer17 changes to div.timer[object Object].

I tried turning the object Object into a string with new String(obj), with json.stringify, etc. Nothing worked. Please help.

My goal is appending str2 to str1, so i can get the wanted selector (for example, div.timer25).

Here's the xml:

<?xml version="1.0" encoding="utf-8" ?>
<products>
<product cookie="The red">
  <timediff>02:28:59</timediff>
  <username>denis</username>
  <price>25</price>
  <id>17</id>
</product>

<product cookie="The red">
  <timediff>00:28:59</timediff>
  <username>denis</username>
  <price>35</price>
  <id>18</id>
</product>
</products>

Upvotes: 0

Views: 992

Answers (4)

Yogurt The Wise
Yogurt The Wise

Reputation: 4489

I believe once you each find "product" you can use them as an object and just call something like $(this).id.

$(xml).find("product").each(function() {

   var str1 = "div.timer";
   var **str2** = $(this).id;


   $("div.timer17").html(str1 + str2);

});

If your using firefox and firebug, place the Object in console.info(someobject); it will usually string out the object.

Upvotes: 1

Ruan Mendes
Ruan Mendes

Reputation: 92274

Your variable str2 is a jQuery objecy, it is not a string. Are you looking for the id attribute of the XML node being iterated?

function parseXml(xml)
{
  $(xml).find("product").each(function() {    
    var str1 = "div.timer";
    var str2 = this.id;
    $("div.timer17").html(str1 + str2);
  });
}

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227270

$(this).find("id") returns an object, this is why it's printing [object Object]. It's a jQuery object, and it can't just be turned into a string, because what should that print out?

If you want the text from the node, try this:

var str2 = $(this).find("id").html();

Upvotes: 1

NullRef
NullRef

Reputation: 3743

Assuming you want the text or html I think you want this

var str2 = $(this).find("id").text();

or

var str2 = $(this).find("id").html();

Upvotes: 5

Related Questions