kaycee kaycee - 1 month ago 7
jQuery Question

How to clone a XML node, change value inside it and append it without changing all nodes with jQuery?

I have a XML document where this particular node is retrieved using

xmldoc.find("main_node")
:

<main_node>
<rule_node>
<rule_name>Default_rule</rule_name>
</rule_node>
</main_node>


I'm trying to clone the
<rule_node>
node, change the
<rule_name>
node value inside it and append it to
<main_node>
node after but I'm always changing all the
<rule_name>
nodes values.

I'm stocking the default
<rule_node>
node inside a variable name
rule_xml
and then performing the clone and value change like this:

for (i=0; i < 3; i++) {
$(rule_xml).clone().appendTo(sld.find("main_node")).find("rule_name").text("Rule_no" + (i+1))
}


It results in this XML which is incorrect:

<main_node>
<rule_node>
<rule_name>Rule_no2</rule_name>
</rule_node>
<rule_node>
<rule_name>Rule_no2</rule_name>
</rule_node>
<rule_node>
<rule_name>Rule_no2</rule_name>
</rule_node>
<rule_node>
<rule_name>Rule_no2</rule_name>
</rule_node>
</main_node>


I tried using the children() function like this but it does not work:

$(rule_xml).clone().children().find("rule_name").text("new_text_here")
.appendTo(sld.find("main_node"))


How can I change the
<rule_name>
node text of the cloned node only ?

Answer

From the result you have given, it looks like your current code is updating each rule_name element at every iteration. However, it's a bit strange that they are all numbered two - I would expect them to all be numbered three (last iteration is 2, and rules are numbered i +1). I've just tested your code and I can't replicate the issue.

Perhaps try this code and see if it works for you:

for (i=0; i < 3; i++) {
    //Clone the node
    var newNode = $(rule_xml).clone();
    //Update that individual node
    newNode.find("rule_name").text("Rule_no" + (i+1));
    //Now append that node
    newNode.appendTo(sld.find("main_node"))       
}
Comments