skip to Main Content

I build my XML with my base XML like this:

$(xml).find('PARENT').find('CHILDREN').each(function(i){
  outputstr += '<lorem id="">'
})

now the Object "parent" exists a few times in every XML I read, I want to count up the ID Attribute to every lorem build.

then my output XML should look like this:

<lorem id="1"/>
<lorem id="2"/>
<lorem id="3"/>

how do I count up each time a Element was build

2

Answers


  1. You can use a template literal to substitute i into the output.

    $(xml).find('PARENT').find('CHILDREN').each(function(i) {
      outputstr += `<lorem id="${i+1}">`
    })
    
    Login or Signup to reply.
  2. You could combine the parent and child selectors into one $.fn.find call.

    const xml = `
    <GRAND_PARENT>
      <PARENT>
        <CHILDREN>a</CHILDREN>
        <CHILDREN>b</CHILDREN>
        <CHILDREN>c</CHILDREN>
      </PARENT>
      <PARENT>
        <CHILDREN>d</CHILDREN>
        <CHILDREN>e</CHILDREN>
        <CHILDREN>f</CHILDREN>
      </PARENT>
    </GRAND_PARENT>
    `;
    
    let outputstr = '';
    $(xml).find('PARENT CHILDREN').each(function(i) {
      const id = i + 1;
      console.log(id);
      outputstr += `<lorem id="${id}">`;
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    As mentioned, you can use the DomParser instead of jQuery. Parsing XML should not require pulling in the jQuery library.

    const xmlStr = `
    <GRAND_PARENT>
      <PARENT>
        <CHILDREN>a</CHILDREN>
        <CHILDREN>b</CHILDREN>
        <CHILDREN>c</CHILDREN>
      </PARENT>
      <PARENT>
        <CHILDREN>d</CHILDREN>
        <CHILDREN>e</CHILDREN>
        <CHILDREN>f</CHILDREN>
      </PARENT>
    </GRAND_PARENT>
    `;
    
    const xmlDoc = new DOMParser().parseFromString(xmlStr, 'text/xml');
    let outputstr = '';
    xmlDoc.querySelectorAll('PARENT CHILDREN').forEach(function(el, i) {
      const id = i + 1;
      console.log(id);
      outputstr += `<lorem id="${id}">`;
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search