kathrynm kathrynm - 3 months ago 17
Javascript Question

Get Hex Values from Kuler API

I'm trying to get each hexadecimal value from the Adobe Kuler API using JQ/JS:

kuler api xml

They provide an xml but I'm having a hard time grabbing the values and placing them in an array like this:

var colors = [E6E2AF, A7A37E, EFECCA, 046380, 002F2F];


The colors exist in this element

<description>
Hex: E6E2AF, A7A37E, EFECCA, 046380, 002F2F
</description>


and here too:

<kuler:swatchHexColor>
E6E2AF
</kuler:swatchHexColor>


If you have any ideas I would really appreciate it,


  • K


Answer

I spent some time to find a selector that works for namespaces. This selector seems to do the job. Credits goes to Fasani for his answer in jQuery - XML parsing with namespaces.

$(xml).find('kuler\\:swatchHexColor, \\swatchHexColor');

Full snippet:

var colors = [];

$.ajax({
    type: "GET",
    url: 'https://kuler-api.adobe.com/rss/get.cfm?listType=popular&itemsPerPage=5&key=mykey',
    dataType: "xml",
    success: function(data){
       // Select all <kuler:swatchHexColor> tags
       var colorHexs = $(data).find('kuler\\:swatchHexColor, \\swatchHexColor');
       
       // Loop through them, push them to colors array, and then append it body
       $(colorHexs).each(function(i, hex){
         
         colors.push($(hex).text()); // push to array
         $('body').append('<div class="color" style="background:#'+$(hex).text()+'">'+$(hex).text()+'</div>');

       });

       // colors output.
       console.log(colors);
      
      
    }
});
.color {
  width:33.334%;
  height:100px;
  float:left;
  text-align:center;
  line-height:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

Credits:

Comments