skip to Main Content

I’m working on displaying an RSS feed in a website through the use of jQuery and AJAX. One of the strings from the source XML file are wrapped in a <category> tag, and there are multiple of these returned. I’m getting the source data like follows:

        var _category = $(this).find('category').text();

Because there are multiple categories returned with this method, say the following:

<category>Travel</category>
<category>Business</category>
<category>Lifestyle</category>

I’m getting strings returned like so:

TravelBusinessLifestyle

My end goal is to see each of these separate strings returned and wrapped in individual HTML elements, such as <div class="new"></div>.

I did end up trying the following:

    var _categoryContainer = $(this)
    .find('category')
    .each(function () {
      $(this).wrap( "<div class='new'></div>" );
    });

among quite a few other variations.

This is all being appended to a HTML structure similar to the following.

        // Add XML content to the HTML structure
        $(".rss .rss-loader")
          .append(
            '<div class="col">'
            + <h5 class="myClass">myTitle</h5>
            + _category
            + "</div>"
          );

Any suggestions would be much appreciated!

2

Answers


  1. if it’s a simple html which is mentioned in a question. you can use something like below.

    var html="<category>Travel</category><category>Business</category><category>Lifestyle</category>"
    var htmlObj=$.parseHTML(html);
    var container=$("#container")
    $.each(htmlObj,function(i,o){
       container.append("<div class='new'>"+o.innerText+"</div>")
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id='container'></div>
    Login or Signup to reply.
  2. Same as first answer, but without jquery

    let container = document.querySelector('div#container');
    document.querySelectorAll('category').forEach(element => {
      let div = document.createElement('div');
      div.innerText = element.innerText;
      container.appendChild(div);
    })
    <category>Travel</category><category>Business</category><category>Lifestyle</category>
    
    <div id="container"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search