1

Hi I'm trying to create a XML from an for-loop. But with this below code I only get the Last element found on the page. Not all of them as I expected.

Consider that there are many elements on the page with id's like "textHolder1, textHolder2 etc. With all different content.

Jquery:

var text = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><canvas>";

text += "<elements>";   
text_length =  $('[id^="textHolder"]').length;  
for(var n = 0; n < text_length; n++){
TextElementID = $('[id^="textHolder"]').attr('id');
TextElementContent = $('[id^="textHolder"]').text();  
text += "<element id='"+TextElementID+"'>";  
text += "<content>"+TextElementContent;  
text += "</content>";  
text += "</element>";  
}
text += "</elements>";         
text +="</canvas>";

alert(text)    

What am I doing wrong here?

2
  • 1
    Inside the for loop you are doing $('[id^="textHolder"]') on each iteration, which selects ALL elements that match the selector. You are then getting the id of the first matched element and the content of the first matched element. That obviously isn't what you want. Commented May 23, 2013 at 14:21
  • Consider using eq selector. Commented May 23, 2013 at 14:22

2 Answers 2

2

Try this, using each loop:

var text = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><canvas>";

text += "<elements>";
$('[id^="textHolder"]').each(function(){
    var TextElementID = this.id,
        TextElementContent = $(this).text();
    text += "<element id='" + TextElementID + "'>";
    text += "<content>" + TextElementContent;
    text += "</content>";
    text += "</element>";
});
text += "</elements>";
text += "</canvas>";

alert(text)
Sign up to request clarification or add additional context in comments.

1 Comment

Well, that is what I call a perfect answer! Thanks! Works like a charm!
0

I see a few issues. I dont see where you're declaring some variables, also, you're selecting a group of elements and trying to get an ID. I believe this code clears it up (not tested);

var text = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><canvas>";

text += "<elements>";   
var text_length =  $('[id^="textHolder"]').length;  

for(var n = 0; n < text_length; n++){
    var TextElementID = $('[id="textHolder' + i + '"]').attr('id');
    var TextElementContent = $('[id="textHolder' + i + '"]').text();  
    text += "<element id='"+TextElementID+"'>";  
    text += "<content>"+TextElementContent;  
    text += "</content>";  
    text += "</element>";  
}
text += "</elements>";         
text +="</canvas>";

alert(text)    

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.