I'm using JS to search in an XML and get it's elements in order to use it in further processing, I'm using heapbox to display the elements and then using .selected to get the selected element in order to display it's children.
The problem here is that i want to get the selected element in order to make some name processing before getting children, but i got nothing when storing it in a var and got it works when using the full query directly,
for ex,
var section = '', text = '' ;
section = $('menu').find($(".selected").text()).attr('nodeName');
alert($('menu').find($(".selected").text()).attr('nodeName'));
in that code section equals nothing, text equals nothing, it alerts undefined, while using $('menu').find($(".selected").text()).attr('nodeName') directly in processing works very good.
UPDATE:
xml file:
<?xml version="1.0" encoding="UTF-8"?>
<menu parent_id="0" >
<Menu cat="main">
</Menu>
<Soup cat="main">
<Mushrom0Tomato.Soap price = "15.95" hasoption = "false">
</Mushrom0Tomato.Soap>
<Cream.Of.Chicken.Soap price = "16.95" hasoption = "true">
<Add.Mushroom price = "3.95"></Add.Mushroom>
<none price = "0"></none>
</Cream.Of.Chicken.Soap>
<Season.Soap price = "15.95" hasoption = "false">
</Season.Soap>
</Soup>
</menu>
JS code:
var cats=[], cati=0, total=0, selectedarray=[], itemoptions=[], optionstring='', section='', si=0, oi=0, items=[];
$("#total").append("Total: " + total + " EGP");
$('#dummy').load('cafe.xml',function() {
initialize();
})
function initialize(){
ct=$('menu').children().length;
for(cati==0;cati<=ct-1;cati++)
{
cats[cati]=$('menu').children().eq(cati).prop('nodeName');
var realname = cats[cati];
if(realname.indexOf(".") != -1){
realname = realname.replace(/\./g,' ');
}
$('.basic-example').append('<option value="option1">'+realname+'</option>');
}
$(".basic-example").heapbox({'onChange':function(){loadmenu()},effect:{type:"fade",speed:"slow"}});
}
// loading the items to the menu
function loadmenu()
{
$("#gallery").empty();
section = $('menu').find($(".selected").text()).attr('nodeName');
alert($("menu .selected").text().toString());
.
.
.
.find is meant for finding children elements of a selected node
You probably just want
$("menu .selected").text();
And
$("menu .selected").attr("nodeName");
The .find equivalent of this (although probably unnecessary) would be
$("menu").find(".selected").text();
And
$("menu").find(".selected").attr("nodeName");
Related
I'm trying to figure out how I can get the XML child element of the current parent element. Right now if I try to get the current child element, if it doesn't exist I just get the next element with this name except an empty result...
I already tried to get all children of this parent element but didn't find any way how to do this...
Currently, my code looks like this:
x = xmlDoc.getElementsByTagName('place');
for (i = 0; i < (x.length - 1) ;) {
type = x[i].getAttribute('type');
console.warn("Typ: " + type);
xname = xmlDoc.getElementsByTagName(type);
name = xname[i].childNodes[0].nodeValue;
txt += name + "<br>";
xroad = xmlDoc.getElementsByTagName("road");
road = xroad[i].childNodes[0].nodeValue;
txt += road + " ";
xnum = xmlDoc.querySelectorAll("house_number");
num = xnum[i].childNodes[0].nodeValue;
txt += num + "<br>";
The XML I'm referring to, or at least parts of it look like this:
<place place_id="57293627" osm_type="node" osm_id="4605575366" place_rank="30" boundingbox="48.8344591,48.8345591,8.2877028,8.2878028" lat="48.8345091" lon="8.2877528" display_name="Rheinau-Bäck, Murgtalstraße, Bischweier, Nachbarschaftsverband Bischweier-Kuppenheim, Landkreis Rastatt, Regierungsbezirk Karlsruhe, Baden-Württemberg, 76476, Deutschland" class="shop" type="bakery" importance="0.001" icon="https://nominatim.openstreetmap.org/images/mapicons/shopping_bakery.p.20.png">
<extratags>
<tag key="opening_hours" value="Mo-Sa 06:00-20:00"/>
</extratags>
<bakery>Rheinau-Bäck</bakery>
<road>Murgtalstraße</road>
<village>Bischweier</village>
<county>Nachbarschaftsverband Bischweier-Kuppenheim</county>
<state_district>Regierungsbezirk Karlsruhe</state_district>
<state>Baden-Württemberg</state>
<postcode>76476</postcode>
<country>Deutschland</country>
<country_code>de</country_code>
</place>
<place place_id="239017" osm_type="node" osm_id="52623297" place_rank="30" boundingbox="48.9310367,48.9311367,8.2681663,8.2682663" lat="48.9310867" lon="8.2682163" display_name="Maier Bäck, 63, Hauptstraße, Durmersheim, Verwaltungsverband Durmersheim, Landkreis Rastatt, Regierungsbezirk Karlsruhe, Baden-Württemberg, 76448, Deutschland" class="shop" type="bakery" importance="0.001" icon="https://nominatim.openstreetmap.org/images/mapicons/shopping_bakery.p.20.png">
<extratags>
<tag key="wheelchair" value="yes"/>
<tag key="contact:phone" value="+49 7245 2338"/>
</extratags>
<bakery>Maier Bäck</bakery>
<house_number>63</house_number>
<road>Hauptstraße</road>
<town>Durmersheim</town>
<county>Verwaltungsverband Durmersheim</county>
<state_district>Regierungsbezirk Karlsruhe</state_district>
<state>Baden-Württemberg</state>
<postcode>76448</postcode>
<country>Deutschland</country>
<country_code>de</country_code>
</place>
As you can see, only the second place has a <house_number> tag. If I would use my code with this XML file, I would get the house number 63 for the first element and no house number for the second element.
It's like if the parent XML doesn't contain a "house_number" element, it just picks the next one it finds - some parent elements later...
I hope I explained it clear enough and I hope it's no duplicate but I didn't find anything and I have literally no idea how I could do this by myself...
Thanks in advance
Niko
The basic problem is you query the whole document inside your loop for child tags of <place>
Therefore the indexing of those full document queries won't match the indexing of <place> used in your loop since there could be more or less of the nested tags
Instead, query within each place instance so a query like:
xnum = xmlDoc.querySelectorAll("house_number");
Would be more like
xnum = x[i].querySelector("house_number");
if(xnum ){
num = xnum.childNodes[0].nodeValue;
}
I am using bootstrap table in my web page and want to get complete textual data from all table cells, when pagination is on. I have tried the following method and it returns all the data:
var data = $('#' + tableID).bootstrapTable('getData')
Now when i traverse data object to get value for every cell it works fine but, for those cells which have some nested html , for example:
<td class="danger">cell 4</td>
<td>
google
</td>
Now, in this case, i want to get value for second cell as google but it returns me whole html as
google
Any idea, how i can get only textual value.
I can't do any server side operation, I have to achieve this using javascript/jquery. I have also tried using jquery:
function getColData(tableID,colIndex) {
var colArray = $('#' + tableID + ' td:nth-child'+'('+colIndex+')').map(function(){
return $(this).text();
}).get();
return colArray
}
it returns data correctly but only which is visible on active page and i want all the data.
Based on your file on JSFiddle I have modified the JS part as follows, this will get you the text on every td(i.e. text or text content) and not the values of their attributes. Basically this traverses through the DOM searching for tags embedded in ones - except for those on the table header - then obtains the text value.
var table = $('#table'), button = $('#button');
button.click(function() {
var data = [];
table.find('tr:not(:first)').each(function(i, row) {
var cols = [];
$(this).find('td').each(function(i, col) {
cols.push($(this).text());
});
data.push(cols);
});
alert(data);
});
You can see it in action here
UPDATE:
This will get you all data regardless of pagination, also it will strip tags and nested tags.
var table = $('#table'), button = $('#button');
button.click(function() {
var messedData = table.bootstrapTable('getData');
var data = [];
$.each(messedData, function(i, row) {
var rowData = {
'name': row['0'],
'star': row['1'],
'forks': row['2'],
'desc': row['3'],
}
for (prop in rowData) {
var tmp = document.createElement("div");
tmp.innerHTML = rowData[prop];
rowData[prop] = tmp.textContent || tmp.innerText || "";
}
data.push(rowData);
});
console.log(data);
});
You can see it here
Since the actual data is coming in as a string, I don't think bootstrap-table can't differentiate it from the other data. The simple solution I can think of is to use substring() to extract the data from the cells that contain custom html.
http://jsfiddle.net/vwg5Lefz/
The alternative is to go through the generated table <td> and use text() to get the text data from the cells.
http://jsfiddle.net/n0djy60v/
I am trying to get prices from between span tags. I would like to have all prices in an array. I cant seem to get it to work, I am guessing my regex is incorrect.
I am looking for any span tags with the class 'amount', the tag has no other attributes set and only has one class. E.g. <span class="amount">£9.99</span>
var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
.map(function(val){
return val;
});
Output
[ '£9.99', '£100.00' ]
I am trying to get prices from between span tags. I would like to have all prices in an array. I cant seem to get it to work, I am guessing my regex is incorrect.
I am looking for any span tags with the class 'amount', the tag has no other attributes set and only has one class. E.g. <span class="amount">£9.99</span>
var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
.map(function(val){
return val;
});
Output
[ '£9.99', '£100.00' ]
* UPDATE *
Turns out it was an encoding with the ajax response resp.fragments['data'].
I was using regex as it is something I have not really used before in JS and thought I would have a play. I did look at many examples and after about 45 mins with no success I thought a fresh set of eyes would fix it.
#spaceman
Thanks for the helpful comment. Your one of those people if someone asked "Is there is a doctor in the house?", you would stand up and say "Sweet load there are loads of doctors out there".
While a regular expression could work for this, it might be easier to simply select the <span class='amount'> elements and map their innerHTML content to an array via the map() function:
// This would yield an array containing your values
var amounts = Array.prototype.slice
.call(document.querySelectorAll('span.amount'))
.map(function(a){ return a.innerHTML; });
You can see a working example of this demonstrated here.
Simplest method will be to add this to an invisible DOM object and then traverse it via DOM API
var text = '<span class="amount">£9.99</span><span class="amount">£9.99</span>'
//now append it to an DOM object
var wrapperDiv = "<div style='display:none' id='tmpDiv'>" + text + "</div>";
document.body.innerHTML += wrapperDiv;
var elements = document.querySelectorAll( "#tmpDiv amount" );
var output = Array.prototype.slice.call( elements ).map( function(val){
return val.innerText;
})
Another approach could be split the text by <span class="amount"> and get the value after first index
DEMO
var text = '<span class="amount">£9.99</span><span class="amount">£9.99</span>'
var output = [];
text.split('<span class="amount">').forEach( function(val, index) {
if (index > 0 )
{
output.push( val.replace( "</span>", "" ) );
}
});
document.body.innerHTML += JSON.stringify( output, 0, 4 );
You can use this instead.
var prices = document.getElementsByClassName('amount');
var price_array = [];
for (i= 0; i < prices.length; ++i) {
price_array.push(prices[i].innerHTML);
}
document.write(" | " + price_array);
<span class='amount'>£123</span>
<span class='amount'>£3</span>
<span class='amount'>£5</span>
<span class='amount'>£64</span>
You don't need to use regex or jQuery for this.
enter code hereI have an html UL control that gets dynamicaly populated with LI (list items).
I want a javascript function to process the items of the list and need a csv of all the list items.
I am trying this and getting errors:
javascript:
var ulTags = document.getElementById("basic_tag_handler");
var listItem = ulTags.getElementsByTagName("li");
var stringOfTags = '';
for (var i = 0; i < listItem.length-1; i++) {
stringOfTags += listItem[i].innerHTML & "," );
}
alert (stringOfTags);
html:
<ul id="basic_tag_handler" runat ="server" ></ul>
You've a syntax error when you have &, I suppose, you meant +. Also, you need to remove the trailing comma, but however better way would be to use Array.map and Array.join
var stringOfTags = [].map.call(listItem, function(elm){
return elm.innerHTML;
}).join(",");
Hi i would like to create an array from the title and src of an image set. Then append it to a list, then clear the array (the images in the set changes) then clear the array and the list. repeat it again and again as the images change in the set.
Here is the HTML:
<div id="imageholder">
<img src="images/a001.png" title="orange"/>
<img src="images/a002.png" title="red apple"/>
<img src="images/a003.png" title="green apple"/>
<img src="images/a004.png" title="red apple"/>
</div>
<ul id="list"></ul>
and here is the code:
title_array = [];
src_array = [];
function sumarychange() {
$("#imageholder img").each(function() {
// pushing each values into arrays
title_array.push($(this).attr("title"));
src_array.push($(this).attr("src"));
// i think this part will append the content in the arrays
var list = $('#list');
var existing_item = $('#list_'+ title);
// removing items with the same titles
if (existing_item.length < 1){
var new_item = $('<li />');
new_item.attr('id', 'list_'+ title);
new_item.html('<div>' + title + '</div><img src="' + src + '" />');
list.append(new_item);
}
});
// i think this will set the arrays back to empty
title_array.length = 0;
src_array.length = 0;
}
this is just a sample. In actual the image has more tags. i have no clue how to empty out the list when this function is called again. im just learning coding now and i have no idea how to correct this to make it work.
This looks to me like an XY problem.
Judging from your example code above as well as your previous question, I'm guessing what you're trying to do is update a list of entries based on the attributes of an existing set of elements, but with items with duplicate titles only displayed once.
Assuming I got that right, here's one way to do it: (demo: http://jsfiddle.net/SxZhG/2/)
var $imgs = $("#imageholder"), $list = $("#list");
function summary_change() {
// store data in tmp obj with title as key so we can easily ignore dups
var store = {};
$imgs.find("img").each(function() {
if (store.hasOwnProperty(this.title)) return; // ignore dup title
store[this.title] = this.getAttribute("src");
});
$list.empty(); // empty the list
for (var title in store) { // add new list items
$("<li>")
.append($("<div>", {"text":title}))
.append($("<img>", {"src":store[title]}))
.appendTo($list);
}
}
Note that if more than one image has the same title, only the src of the first one is used in the summary results. If you wish to use the src of the last item found, simple remove the line if (store.hasOwnProperty(this.title)) return;.