I'm trying to create a menu from an xml file, via jquery.
I need to run the script for this, on window-load.
It's a dropdown menu with some jquery code to it in my plugins.js
I'm trying to completely add all the items of the xml to the UL of the menu list class...
Here's the code in which I need to add my menu to:
HTML
<li class="w-nav-item level_1 has_sublevel">
<a class="w-nav-anchor level_1" href="#">
<span class="w-nav-icon"><i class="fa fa-files-o"></i></span>
<span class="w-nav-title">Animals</span>
<span class="w-nav-arrow"></span>
</a>
<!-- level 2 -->
<ul class="w-nav-list level_2">
<!---------------1 START animals with sublevel---------------->
<li class="w-nav-item level_2 has_sublevel">
<a class="w-nav-anchor level_2" href="javascript:void(0);">
<span class="w-nav-title">Birds </span>
<span class="w-nav-arrow"></span>
</a>
<!-- level 3 -->
<ul class="w-nav-list level_3">
<li class="w-nav-item level_3">
<a class="w-nav-anchor level_3" href="animals/1_sparrow.html">
<span class="w-nav-title">Sparrow</span>
<span class="w-nav-arrow"></span>
</a>
</li>
<li class="w-nav-item level_3">
<a class="w-nav-anchor level_3" href="animals/1_crow.html">
<span class="w-nav-title">Crow</span>
<span class="w-nav-arrow"></span>
</a>
</li>
</ul>
</li>
<!---------------END animals with sublevel------------------>
<!---------------2 START animals with sublevel---------------->
<li class="w-nav-item level_2 has_sublevel">
<a class="w-nav-anchor level_2" href="javascript:void(0);">
<span class="w-nav-title">Carnivorous Animals</span>
<span class="w-nav-arrow"></span>
</a>
<!-- level 3 -->
<ul class="w-nav-list level_3">
<li class="w-nav-item level_3">
<a class="w-nav-anchor level_3" href="animals/2_tiger.html">
<span class="w-nav-title">Tiger</span>
<span class="w-nav-arrow"></span>
</a>
</li>
</ul>
</li>
<!---------------END animals with sublevel------------------>
<!---------------3 START animals with sublevel---------------->
</li>
<!---------------END animals with sublevel------------------>
And here's the XML From which I need to create the menu..:
XML
<items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<item>
<animal_id>1_1</animal_id>
<animal_title>Sparrow </animal_title>
<animal_generic>A Sparrow Bird</animal_generic>
<animal_category>Birds </animal_category>
<animal_code>Code 152</animal_code>
<animal_img>images_animals/1_1_sparrow.png</animal_img>
<animal_url>1_sparrow.html</animal_url>
</item>
<item>
<animal_id>1_2</animal_id>
<animal_title>Crow</animal_title>
<animal_generic>A Crow Bird</animal_generic>
<animal_category>Birds </animal_category>
<animal_code>Code 153</animal_code>
<animal_img>images_animals/1_2_crow.png</animal_img>
<animal_url>1_crow.html</animal_url>
</item>
<item>
<animal_id>2_1</animal_id>
<animal_title>Tiger </animal_title>
<animal_generic>A Wild Tiger</animal_generic>
<animal_category>Carnivorous Animals </animal_category>
<animal_code>Code 151</animal_code>
<animal_img>images_animals/2_1_tiger.png</animal_img>
<animal_url>2_tiger.html</animal_url>
</item>
...
...
...
I'm trying to append all the "items" in the xml to the menu, as per the div format of li list. After the <ul class="w-nav-list level_2">
I have this code, that I was using to add "countries" to in my contact form, but I don't know how to change it to add the required divs.
not related to the question, but a simple code
var cList = $('ul.w-nav-list.level_2')
$.each(data, function(i)
{
var cat_no = data.id.split('_');
var opt = $('<option/>')
.attr('value', countries[i])
.text(countries[i])
.appendTo(cList);
});
I have the XML id in the format of:
XML ID format
1_1: first item, category 1,
1_2: second item, category 1,
1_3: third item, category, 1,
2_1: fourth item, category 2,
3_1: fifth item, category 3,
..... like this there are about 10-13 categories with about 100 xml items.
I believe something of this sort should do:
ajax: xml_url, etc
xml response, data ,
data.xml_id.split('_'); //to get the first element of the xml id, but I guess this would only return the last element. Don't know how to change it to return first element.
function add_menu(){
$('ul.w-nav-list level_2').append(data, function ( ){ for(i=0;i<=data.length) for all data.xml_id==i: add category + item divs, li, ul, /li, /ul) }
The above is just a kindof alogrithm or a way of how I think this can be done... I don't know how to do this in jquery/javascript.
Here's what I'm trying to do in javasacript/jquery:
Javascript
var animalsXMLurl = 'http://dl.dropboxusercontent.com/u/27854284/Stuff/Online/XML_animals.xml';
$(function() {
$.ajax({
url: animalsXMLurl, // name of file you want to parse
dataType: "xml",
success: function parse(xmlResponse){
var data = $("item", xmlResponse).map(function() {
return {
id: $("animal_id", this).text(),
title: $("animal_title", this).text(),
url: $("animal_url", this).text(),
category: $("animal_category", this).text().split('/'),
};
}).get();
var categnumber = new Array();
for(i=0;i<=data.length;i++) //for splitting id, and getting 0 for category_number (1 or 2 or 3...and so on)
{ categnumber[i] = data[i].id.split('_');
console.log(categnumber[i][0]);
for(j=0;j<=data.length;j++) //appending via a function.
{ var data_text = category_or_animal(data, categnumber, j);
console.log(data_text);
$('ul.w-nav-list.level_2').append( data_text );
}
}
function category_or_animal(d, catg, k){
var catg1 = new Array();
var catg2 = new Array();
var catg1 = d[k].id.split('_');
if(d[k-1]){
var catg2 = d[k-1].id.split('_');
//if(d[k-1].id)
if (catg1[0] != catg2[0])
return category_gen(d,k);
} else return '</ul>' + animal_gen(d,k);
}
function category_gen(d,z){
var category_var = '<li class="w-nav-item level_2 has_sublevel"><a class="w-nav-anchor level_2" href="javascript:void(0);"><span class="w-nav-title">' + d[z].category + '</span><span class="w-nav-arrow"></span></a><ul class="w-nav-list level_3">';
return category_var;
}
function animal_gen(d,z){
var animal_var = '<li class="w-nav-item level_3"><a class="w-nav-anchor level_3" href="animals/' + d[z].url + '"><span class="w-nav-title">' + d[z].title + '</span><span class="w-nav-arrow"></span></a></li>';
return animal_var;
}
}, error: function(){console.log('Error: Animals info xml could not be loaded.');}
});
});
Please could someone provide help regarding this?
Here's the jsfiddle WITHOUT the menu filled in html: http://jsfiddle.net/mohitk117/d7XmQ/2/
And here's the jsfiddle, WITH the menu filled in html, this is the a general idea of what I'm trying to get in the menu, but only being created dynamically via jquery+xml and not hardcoded like the html example here: http://jsfiddle.net/mohitk117/r6LQg/
I didn't know how to upload the xml to the fiddle, and also didn't know what javascript code to write down, so I kept the code similar to an alogrithm.
EDIT:
Updated the javascript code... +
Updated jsfiddle: http://jsfiddle.net/mohitk117/d7XmQ/4/
Thanks..
I asked another question for the same problem, but the new question was different. And I received a reply from DannyFritz with the answer. His code perfectly exhausts the xml file and puts the revelant fields into a list format. That was not completely what I was trying to do, but after some additions and minor easier changes, I got the menu functioning.
Here's the complete edited code of my version of the xml based menu: [ ::: JsFiddle ::: ]
"use strict";
var animalsXMLurl = 'http://dl.dropboxusercontent.com/u/27854284/Stuff/Online/XML_animals.xml';
$(function () {
var $menu = $('.w-nav-list.level_2');
$.ajax({
url: animalsXMLurl, // name of file you want to parse
dataType: "xml",
success: handleResponse,
error: function () {
console.log('Error: Animals info xml could not be loaded.');
}
});
function handleResponse(xmlResponse) {
var $data = parseResponse(xmlResponse);
createMenu($data);
}
function parseResponse(xmlResponse) {
return $("item", xmlResponse).map(function () {
var $this = $(this);
return {
id: $this.find("animal_id").text(),
title: $this.find("animal_title").text(),
url: $this.find("animal_url").text(),
category: $this.find("animal_category").text()
};
});
}
function createMenu($data) {
var categories = {};
$data.each(function (i, dataItem) {
if (typeof categories[dataItem.category] === 'undefined') {
categories[dataItem.category] = [];
}
categories[dataItem.category].push(dataItem);
});
for (var category in categories) {
var categoryItems = categories[category];
$menu.append($('<li class="w-nav-item level_2 has_sublevel">').html('<a class="w-nav-anchor level_2" href="javascript:void(0);"><span class="w-nav-title">' + category + '</span><span class="w-nav-arrow"></span></a>' + createCategory(categoryItems) + '</li>'));
} //console.log($menu.html());
}
function createCategory(categoryItems) {
var $list = $('<p>');
$.each(categoryItems, function (i, dataItem) {
var $item = $('<li class="w-nav-item level_3"></li>')
.html('<a class="w-nav-anchor level_3" href="' + dataItem.url + '"><span class="w-nav-title">' + dataItem.title + '</span><span class="w-nav-arrow"></span></a>');
$list.append($item);
});
var list_array = ['<ul class="w-nav-list level_3">' , '</ul>'];
return list_array[0] + $list.html() + list_array[1];
}
function createItem() {}
});
I found a solution using an AJAX request and jQuery.parseXML based on this question:
Load xml from javascript
$(function() {
$.get(
'animals.xml',
{},
function(data) {
xml = $.parseXML(data);
populateMenu(xml);
});
function populateMenu(xml) {
xml_items = xml.getElementsByTagName('item');
for(var i in xml_items) {
var animal_id = xml_items[i].childNodes[1].innerHTML;
var animal_title = xml_items[i].childNodes[3].innerHTML;
var animal_generic = xml_items[i].childNodes[5].innerHTML;
var animal_category = xml_items[i].childNodes[7].innerHTML;
var animal_code = xml_items[i].childNodes[9].innerHTML;
var animal_img = xml_items[i].childNodes[11].innerHTML;
var animal_url = xml_items[i].childNodes[13].innerHTML;
$('.w-nav-list.level_3').append('<li class="w-nav-item level_3"><a class="w-nav-anchor level_3" href="'+animal_img+'"><span class="w-nav-title">'+animal_title+'</span><span class="w-nav-arrow"></span></a></li>');
}
}
});
The code can be highly optimized, but it can help you to figure out how to do it.
Here is a working jsfiddle.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I would like to create a menu from multiple JSON files.
Please see the following: https://jsfiddle.net/varJSFiddle/teghqov0/10/
The desired output would be a dynamic menu that looks something like:
<ul class="filter-menu-wrapper">
<li class="filter-menu is-active" id="filter-menu_01"><span class="filter-category">Type<i class='cstm-icon-glyph cstm-icon-glyph-plus'></i></span>
<div class="filter-options">
<span class="filter-option" data-filter="">any</span>
<span class="filter-option" data-filter=".TypeHuman">Human</span>
<span class="filter-option" data-filter=".TypeBlue">Blue</span>
<span class="filter-option thefirst" data-filter=".TypeRed">Red</span>
<span class="filter-option" data-filter=".TypeSpirit">Spirit</span>
</div>
</li>
<li class="filter-menu" id="filter-menu_02"><span class="filter-category">Special<i class='cstm-icon-glyph cstm-icon-glyph-plus'></i></span>
<div class="filter-options">
<span class="filter-option" data-filter="">any</span>
<span class="filter-option" data-filter=".SpecialFireflies">Fireflies</span>
<span class="filter-option" data-filter=".SpecialButterfly">Butterfly</span>
<span class="filter-option" data-filter=".SpecialFoxFire">Fox Fire</span>
<span class="filter-option" data-filter=".SpecialSmoke">Smoke</span>
<span class="filter-option" data-filter=".SpecialSakura">Sakura</span>
<span class="filter-option" data-filter=".SpecialFire">Fire</span>
<span class="filter-option" data-filter=".SpecialEarth">Earth</span>
<span class="filter-option" data-filter=".SpecialWater">Water</span>
<span class="filter-option" data-filter=".SpecialLightning">Lightning</span>
</div>
</li>
<li class="filter-menu" id="filter-menu_03"><span class="filter-category">Clothing<i class='cstm-icon-glyph cstm-icon-glyph-plus'></i></span>
<div class="filter-options">
<span class="filter-option" data-filter="">any</span>
<span class="filter-option" data-filter=".ClothingLightKimono">Light Kimono</span>
<span class="filter-option" data-filter=".ClothingMaroonYukata">Maroon Yukata</span>
<span class="filter-option" data-filter=".ClothingBlueKimono">Blue Kimono</span>
<span class="filter-option" data-filter=".ClothingGreenYukata">Green Yukata</span>
</div>
</li>
</ul>
i think you need like below output , try it, comment if query
$(document).ready(function() {
// 1.) create an attributes (trait) array
// 2.) loop through the items, check if the trait is already in the array, if not then add it
// 3.) loop over attributes array and create the menu items off that.
var loopFunction = function(dataIsLoading) { // the loop
var itemURI = "https://ikzttp.mypinata.cloud/ipfs/QmQFkLSQysj94s5GvTHPyzTxrawwtjgiiYS2TBLgrvw8CW/"
var myArray = []; // create an array to capture all traits
for (let i = 0; i < 4; i++) {
$.getJSON(itemURI+i, function(data) {
var menuItems = "";
var headings = "";
var subheadings = "";
var dataFilter = "";
$.each(data.attributes,function(index,entry) { // i (index), e (entry)
headings = entry.trait_type;
subheadings = entry.value;
dataFilter = entry.trait_type + entry.value;
dataFilter = dataFilter.replace(/ /g, '');
menuItems += '<li class="category"><b>' + headings + '</b>: <br/> ';
menuItems += subheadings + ', ';
menuItems += dataFilter;
menuItems += '</li>'
myArray += entry.trait_type + ': ' + entry.value;
});
$('#myList').html(menuItems);
$('#dump').html(myArray);
//console.log(myArray);
});
}
};
$.when(loopFunction()).done(function() {
var secondaryFunction = function(secondary) { // the loop
// alert("it's done, sort and display");
}
secondaryFunction();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id ="myList">
</ul>
MAYUR, I ended up with the following. It works perfectly however it is a little slow. If you have any tips on improving the speed, let me know:
$(document).ready(function() {
// 1.) create an attributes (trait) array
// 2.) loop through the items, check if the trait is already in the array, if not then add it
// 3.) loop over attributes array and create the menu items off that.
var getItemData = async function(id) {
const itemURI = "https://ikzttp.mypinata.cloud/ipfs/QmQFkLSQysj94s5GvTHPyzTxrawwtjgiiYS2TBLgrvw8CW/"
return await $.getJSON(itemURI+id);
}
var loopFunction = async function(dataIsLoading) {
var items = {};
var promises = [];
for (let i = 0; i < 1000; i++) {
// Get data and add to promises array:
promises.push(getItemData(i));
}
// Wait on all promises:
return await Promise.all(promises).then(function(promise) {
// Loop over each returned promise:
$.each(promise, function(index, data) {
// Loop over attribute data:
$.each(data.attributes, function(index, entry) {
let menuParent = entry.trait_type;
let menuChild = entry.value;
let menuParentItem = {};
// Check for menuParent:
if (items.hasOwnProperty(menuParent)) {
// Get menuParent:
menuParentItem = items[menuParent];
}
// Check for menuChild:
if (!menuParentItem.hasOwnProperty(menuChild)) {
// Add menuChild:
menuParentItem[menuChild] = menuChild;
}
// Update items object:
items[menuParent] = menuParentItem;
});
});
// Return items.
return items;
});
};
$.when(loopFunction()).done(function(items) {
// Loop over all items creating the markup.
var menuItems = '';
$.each(items, function(menuParent, menuChildren) {
menuItems += '<li class="menuParent"><b>' + menuParent + '</b>: <ul>';
// Loop over menuChildren.
$.each(menuChildren, function(menuChild, menuChildValue) {
menuItems += '<li class="menuChild">' + menuChild + '</li>';
});
menuItems += '</ul></li>';
});
// Render menu items.
$('#myList').append(menuItems);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id ="myList">
</ul>
I have a simple MVC view which the department name. There is a hierarchy on the department which I use in the nested Treeview node.
My current approach shows the TREEVIEW but only stops by 1 nested.
I want to display all the existing department hierarchy in the Treeview. Something like the figure below:
> Galaxy Department
|
|___> Moon Department
|
|____> Starts Department
|
|___> Cloud department
|
|___> And so on....
My mvc View:
<div class="col-md-3" style="border:1px solid black; height:725px; background-color:#FAFAFA">
<span style="font-weight:500;">Triple4</span>
#{
<div class="treeview">
#{
if (Model != null && Model.Count() > 0)
{
<ul>
#foreach (var i in Model)
{
<li>
<span class="collapse collapsible" data-loaded="false" pid="#i.DepartId"> </span>
<span>
#i.DepatName
</span>
</li>
}
</ul>
}
}
</div>
}
</div>
My Ajax :
$(".collapsible").on("click", function (e) {
e.preventDefault();
var this1 = $(this); // Get Click item
var data = {
pid: $(this).attr('pid')
};
var isLoaded = $(this1).attr('data-loaded'); // Check data already loaded or not
if (isLoaded == "false") {
$(this1).addClass("loadingP"); // Show loading panel
$(this1).removeClass("collapse");
// Now Load Data Part1
$.ajax({
url: "/Department/GetTreeViewList/",
type: "GET",
data: data,
dataType: "json",
success: function (d) {
$(this1).removeClass("loadingP");
if (d.length > 0) {
var $ul = $("<ul></ul>");
//var result;
$.each(d, function (i, ele) {
$ul.append(
$("<li></li>").append(
"<span class='collapse collapsible' data-loaded='false' pid='" + ele.DepartId + "'> </span>" +
"<span><a href='" + ele.NavUrl + "' id='directavail' >" + ele.DepatName + "</a></span>"
)
)
});
//$("[data-role=collapsible]").trigger("collapse");
$(this1).parent().append($ul);
$(this1).addClass('collapse');
$(this1).toggleClass('collapse expand');
$(this1).closest('li').children('ul').slideDown();
}
else {
// no sub menu
$(this1).css({ 'dispaly': 'inline-block', 'width': '15px' });
}
$(this1).attr('data-loaded', true);
},
error: function () {
alert("Error!");
}
});
}
else {
// if already data loaded
$(this1).toggleClass("collapse expand");
$(this1).closest('li').children('ul').slideToggle();
}
});
Any Subjection is very welcome.
I have found a very good approach from #Sourav Mondal
TreeView on Demand
Very quick and Accurate approach which I had to some changes on a JS script since it's old.
And the link it's just a tutorial and guideline.
Hopefully, it's helping someone too.
I have the following html structure:
<div id="gw-sidebar" class="gw-sidebar">
<div class="nano-content">
<ul class="gw-nav gw-nav-list">
<li class="init-un-active"> <span class="gw-menu-text">Scenarios</span> </li>
//===>Need to add the new list using Jquery here
</ul>
</div>
</div>
I want to add a list as shown below using jquery to the class 'init-un-active' shown above:
<li class="init-arrow-down"> <span class="gw-menu-text">Scenario-1</span> <b class="gw-arrow"></b>
<ul class="gw-submenu">
<li> Scenario </li>
<li> Resolutions </li>
<li> Triggers </li>
</ul>
</li>
How do i use jquery to add this code dynamically to the aforementioned class?
I have tried the following but it wont work:
<script type="text/javascript">
function loadScenarioForm () {
SideMenu.createBaseEntry();
// ScenarioForm.create();
}
var SideMenu = {
container : null,
scenarioCount : 0,
scenarioTxt : "Scenario",
ResolutionsTxt : "Resolutions",
TriggersTxt : "Triggers",
menuLink : "javascript:void(0)",
subMenuLink1 : "javascript:void(0)",
subMenuLink2 : "javascript:void(0)",
subMenuLink3 :"javascript:void(0)",
createBaseEntry : function createDefault () {
this.container = $(document.createElement('div'));
this.container.addClass('gw-sidebar');
var html = "";
html += '<div id="gw-sidebar" class="gw-sidebar">';
html += '<div class="nano-content">';
html += '<ul class="gw-nav gw-nav-list">';
html += '<li class="init-un-active"> <span class="gw-menu-text">Scenarios</span> </li>';
html += '</ul></div></div></div>';
this.container.append(html);
$('body').append(this.container);
this.scenarioCount++;
this.container.append(this.createEntry(scenarioCount));
},
createEntry : function createDefault (index) {
var list = $('ul.mylist');
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(list);
return list;
},
</script>
Please advise,
Thanks!
You can make your <li> as a template and append it to the <ul> using jquery. You can try something like this Fiddle:
$(document).ready(function(){
$('a').click(function() {
var template = $('#hidden-template').html();
$('.gw-nav').append(template);
});
});
if ($(".init-un-active").length == 0) {
$.ajax({
url: 'URL From where you want to load ...',
type: 'POST',
data: { id: ID}, // pass your data here if any .. else keep empty
success: function (data) {
$(".init-un-active").css({ "display": "block", "z-index": "999999999999" });
$(".init-un-active").html(data);
},
error: function () {
alert('Unable to load menu...');
}
});
}
else {
if ($(".init-un-active ul").length > 0) {
$(".init-un-active ul").css("display", "none");
$(".init-un-active").css("display", "block");
}
}
Explanation:
if ($(".init-un-active").length == 0)
This condition is used to check if there are already item loaded in li .. if yes then no need to call ajax.. just hide show that menu..
$(".init-un-active").css({ "display": "block", "z-index": "999999999999" });
this css is applied to show menu infront and hide all content beside this menu..
this.container.append(html);
$('body').append(this.container);
instead of this try this
$(".init-un-active").html(html);
I have a JSON witch looks something like this
{
"English": "en",
"Francais": "fr",
"German": "gm"
}
Now I need to print this data in HTML structure witch looks like this
<ul id="links">
<li class="home">
</li>
<li class="languages">
EN ------ > FIRST LANGUAGE FROM JSON
<ul class="available"> ----> OTHERS
<li>DE</li>
<li>IT</li>
<li>FR</li>
</ul>
</li>
</ul>
In javascript I know how to get data and print all data in the same structure but how to do it in structure shown in example ?
in Javascript I'm getting data with
$.getJSON('js/languages.json', function(data) {
console.log(data);
/* $.each(data, function(key, val) {
console.log(val);
});*/
});
Use jQuery template to bind the Html. Some Sample
Something like that:
var getBlock = function(skipLang) {
var str = '\
<ul id="links">\
<li class="home">\
\
</li>\
<li class="languages">\
' + data[skipLang] + '\
<ul class="available">\
';
for(var lang in data) {
if(lang != skipLang) {
str += '<li>' + lang + '</li>';
}
}
str += '</ul></li></ul>';
return str;
}
var html = '';
for(var lang in data) {
html += getBlock(lang);
}
Although using templating engine is an option for simpler code, for this case you can directly run a for loop and assign HTML within javascript code easily.
HTML part is going to be something like this
<ul id="links">
<li class="home">
home
</li>
<li class="languages">
<ul class="available">
</ul>
</li>
</ul>
And JS part is like this:
var data = {
"English": "en",
"Francais": "fr",
"German": "gm"
};
var $liLanguages = $('li.languages');
var $ulAvailable = $('ul.available');
var selectedLanguage = '';
for(var index in data) {
if(selectedLanguage == '') {
selectedLanguage = data[index];
$liLanguages.prepend("<a href='#'>" + data[index].toUpperCase() + "</a>");
}
else {
$ulAvailable.append("<li><a href='#'>" + data[index].toUpperCase() + "</a></li>");
}
}
Here is the jsfiddle related.
Hope this helps.
Here is a bit that will get you two new objects, one for the first object property/value and another for the remaining. Still not clear what is done with it once you have it, but let me know if it helps:
// This can be replaced with existing data or updated to var langs = data;
var langs = {"English": "en", "Francais": "fr","German": "gm" };
// jQuery map only works on objects after 1.6, heads up
var lang_keys = $.map( langs, function( value, key ) {
return key;
});
// Now that you have an array of the keys, you can use plain-ol shift()
var primary_lang_key = lang_keys.shift();
// create and populate an object just for your first language:
var primary_lang = {};
primary_lang[primary_lang_key] = langs[primary_lang_key];
// Thanks to shift, we know that populating this object with lang_keys will
// only have remaining items:
var other_langs = {};
$.map( lang_keys, function( lang_key ) {
other_langs[lang_key] = langs[lang_key];
});
console.log(other_langs);
Below is the HTML that I have
<ul id="QBS">
<li>
<a class="qb_mode starting Rodgers" href="#">See Stats</a>
</li>
<li>
<a class="qb_mode Manning" href="#">See Stats</a>
</li>
<li>
<a class="qb_mode Brady" href="#">See Stats</a>
</li>
</ul>
I want to find this unordered list, then tell which item has the starting qb class and then return the class that has their name (brady rodger manning) etc.
What's throwing me in a loop is the fact that the link is wrapped in the list element.
Here is what I am trying:
element = $("#qbs"); // pretty sure I want this vs getElementbyDocumentID
children = element.children();` // gets me all the list elements
for (i=0;i<children.length;i++) {
grandchild = children[i].children();
???? How would I get the 3rd class on this element?
}
Sorry about the formatting.
How about this?
var allClasses = $("#QBS").find('li a[class^="qb_"]')
.map(function () {
return this.className.split(" ").pop();
}).get();
console.log(allClasses);
Fiddle
Provided the class started with qb_* is at the beginning and you want to take only the last class of the match.
if all your class names are qb_mode then:
var allClasses = $("#QBS").find('.qb_mode').map(function () {
return this.className.split(" ").pop();
}).get();
if you want all of them then:
var allClasses = $("#QBS").find('.qb_mode').map(function () {
var cls = this.className.replace(/qb_mode/,'');
return cls.trim().split(/\W+/);
}).get();
console.log(allClasses);
Fiddle
If I understood you correctly, how about:
var name = $('#QBS a.qb_mode.starting').prop('class').replace(/\s*(qb_mode|starting)\s*/g,'');
console.log(name); // Rogers
See demo here.
a=document.getElementById('QBS');
var b=a.getElementsByClassName("qb_mode");
var i, j=b.length, result=[];
for(i=0;i<j;i++) {
c=b[i].className.split(" ");
result.push(c.pop());
}
return result;
fiddle http://jsfiddle.net/3Amt3/
var names=[];
$("#QBS > li a").each(function(i){
var a=$(this).attr("class").split(" ");
names[i]=a[(a.length-1)];
console.log("Name is " + names[i]);
});
or a more precise selector
$("#QBS > li a.qb_mode").each( ....