Html collection has a .length but undefined .item(*) - javascript

I have a function that calls to an xml page, picks out elements by the tag names, and I'm trying to call back a specific one. code so far is:
var xmlDoc = loadXMLDoc("test.xml");
var x = xmlDoc.getElementsByTagName("tagname");
var PittWins = x.item(2);
This will come back [object element]
var xmlDoc = loadXMLDoc("test.xml");
var x = xmlDoc.getElementsByTagName("tagname");
var PittWins = x[2].data;
The above code gives me undefined.
var xmlDoc = loadXMLDoc("nhl.xml");
var x = xmlDoc.getElementsByTagName("tagname");
var PittWins = x.length;
when entered above, i get a result which is correct.
I am trying to understand why it's giving me a length and not a specific node..

What about var PittWins = x[2];?
Re: OP edit
You're saying that x.item(2) and x.length return what you expect, but x[2].data does not? Why do you expect the element to have a data property? Are you trying to write the bracketed version of x.item(2)?
x.item(2) is equivalent to x[2].
x.item(2).data is equivalent to x[2].data.
What are you trying to do? Also, you've used different XML file names and tag names across your different examples. Is this intentional?
Edit #2
To retrieve the text content of an element, use Node.textContent or Node.nodeValue. Your code might look like this, then:
var PittWins = x[2].textContent;

Related

Trying to parse special characters to retrieve JSON element in JavaScript

I need help on a university project I am working on with NodeRed. I am integrating a JSON API in JS (NodeRed) and hit a roadblock. Here's the kind of JSON I'm retrieving:
{"#SpeciesCode":"NO2","#MeasurementDateGMT":"2016-04-04 00:00:00","#Value":"58.2"}
That "#" sign is really giving me all sorts of troubles because wether I use JSON.parse or stringify or escaping, it is either telling me " Unexpected token #" or just "undefined value".
Here is the code I'm working with:
var body = msg.payload;
var bodyParsed = JSON.parse(body);
var data = bodyParsed.AirQualityData.Data;
var valueStr="#Value";
var value=JSON.stringify(valueStr);
var valueParsed=JSON.parse(value);
var element = data[0].valueParsed;
return {payload:element};
If you want to have a go at it, here's the URL to the data: http://api.erg.kcl.ac.uk/AirQuality/Data/Site/SiteCode=WM6/StartDate=2016-04-04/EndDate=2016-05-04/Json
[UPDATE: SOLVED] Thanks to jcubic who provided the solution in the comments below:
to access property using a variable you need to use bracket notation:
var element = data[0][valueParsed]; also you don't need to stringify and parse #value just use data[0]["#Value"]
So the new code is
var body = msg.payload;
var bodyParsed = JSON.parse(body);
var data = bodyParsed.AirQualityData.Data;
var element = data[0]["#Value"];
return {payload:element};

Looping through array and input value into field

I have a general question about a script to automate value inputs & clicking. The purpose is to select a site in the sites variable/concat into ns1 - ns2, click id add_gridVanity place the values into the input field and submit/close then repeat the process until the end of the array. I can't seem to get the for loop running. Sorry for the basic question.
sites = ["stonegrillla.com","schoolfoodbloomingroll.com","chapmanpizzeria.net","sushimasu.com","hmsbountyla.com","pailinthaicuisine.net","fullhouseseafood.com","cjssgourmetdelicatessen.com","bullsheadexpress.net","breakingbreadsf.net","lscaffe.net","latortagorda.org","pinecrestdiner.net","sunriserestaurant.net","tressf.net","hanazensf.com","piperade.org","mazzatsf.net","gaylordindia.net","thegrovefillmore.com","itstopscoffeeshop.net"]
for (i=0; i<sites.length; i++){
var base = 'ns1,ns2.';
var full = base.concat(sites[i]);
var sub1 = "ns1.".concat(sites[i]);
var sub2 = "ns2.".concat(sites[i]);
var both = sub1+'\n'+sub2;
$("#add_gridVanity").click();
$("#name").val(full);
$("#servers").val(both);
$("#sData").click();
$("#cData").click();
console.log(sites[i]); //test
};
Few basic stuff, you need to declare variables and add semicolons. Just declared sites and i and semicolon after sites. The tricky part about javascript is even with one small error with syntax or comma or semicolon etc, entire thing would fail and you wouldn't realize the same, since it might be very silly. Use dev tools in browser to check errors
var sites = ["stonegrillla.com","schoolfoodbloomingroll.com","chapmanpizzeria.net","sushimasu.com","hmsbountyla.com","pailinthaicuisine.net","fullhouseseafood.com","cjssgourmetdelicatessen.com","bullsheadexpress.net","breakingbreadsf.net","lscaffe.net","latortagorda.org","pinecrestdiner.net","sunriserestaurant.net","tressf.net","hanazensf.com","piperade.org","mazzatsf.net","gaylordindia.net","thegrovefillmore.com","itstopscoffeeshop.net"];
for (var i=0; i<sites.length; i++){
var base = 'ns1,ns2.';
var full = base.concat(sites[i]);
var sub1 = "ns1.".concat(sites[i]);
var sub2 = "ns2.".concat(sites[i]);
var both = sub1+'\n'+sub2;
$("#add_gridVanity").click();
$("#name").val(full);
$("#servers").val(both);
$("#sData").click();
$("#cData").click();
console.log(sites[i]); //test
}
Above answer is only for I can't seem to get the for loop running. Once you have the loop running i think you should be able to figure out the rest

Getting "InvalidCharacterError: String contains an invalid character" for an option in list box

I have the following line in my jsp file:
var option = document.createElement('<option value="NO">');
Not sure why this gives me InvalidCharacterError.
Any alternatives?
You can use this code to add to your tag.
var myoption = document.createElement("option");
myoption.setAttribute("value", "carvalue");
var text = document.createTextNode("maruti");
myoption.appendChild(text);
document.getElementById("mySelect").appendChild(myoption);
There was a change in DOM implementation.
Before, you could create a new element with the code inside, for instance:
BAD
var anElement = document.createElement("StackOverflow")
This implementation now, returns this ‘InvalidCharacterError’.
What you must do now is to create the element and to populate it using the innerHTML attribute or the different specific attributes for any node.
GOOD
var anElement = document.createElement("a")
anElement.innerHTML = ("StackOverflow")

Can't display XML element name using Javascript

I have an HTML5 file with javascript to read in a local XML file.
One element in the XML structure is dynamic and contains inner xml, no value.
When trying to display this nodename on the webpage all I see is #text.
Example XML:
<Students>
<student id="1">
<Connor>
<age>20</age>
<gender>male</gender>
</Connor>
</student>
<student id="2">
<Fiona>
<age>25</age>
<gender>female</gender>
</Fiona>
</student>
</Students>
Javascript:
var x = xmlDoc.getElementsByTagName("student");
for(i = 0; i < x.length; i++)
{
var id = x[i].getAttribute("id");
var name = x[i].childNodes[0].nodeName; // produces '#text'
// var name = x[i].firstChild.nodeName; // produces '#text'
document.write("<p>name = " + x[i].childNodes[0].nodeName + "</p>"); // produces '#text'
var age = x[i].getElementsByTagName("age")[0].childNodes[0].nodeValue;
var gender = x[i].getElementsByTagName("gender")[0].childNodes[0].nodeValue;
var student= {id:id, name:name, age:age, gender:gender };
}
In my XML example I understand that the name of the student could be better stored but this is just an example based on a fixed XML structure I'm working with.
Furthermore: reading and displaying the XML file only works whilst running through the IDE. I would eventually like to be able to run the .html file and have the javascript code read the xml file (stored in the same location as the html file) and displays its data.
Edit: First part is solved. Still could use help on the "Furthermore" above.
Ahh this old chestnut, I had the same problem, try
var name = x[i].children[0].nodeName;
This should only get the first xml.
Basicallly the problem is in your list you have 0:text 1:XMLNode, 2:XMLnode ect.
And to get only xml stuff, you can use children rather then childNodes, very similar to HTML Elements
EDIT this example doesn't work
The actual answer:
You need to check the typeof child by using typof when looping throught
I have found a suitable answer for the first part of my question which appears to be a duplicate of:
Javascript/XML - Getting the node name
I've only seen this now in the related questions to my own. It wasn't shown to me when searching or when writing my question. So props to #T.J. Crowder
my solution is:
var nameNode = x[i].firstChild;
while(nameNode.nodeType != 1)
{
nameNode = nameNode .nextSibling;
}
var name = nameNode;

Uncaught TypeError: undefined is not a function

I'm making a plug-in where I can shorten the title of each entry in a forum index if it is too long. However, that is much harder than I expected.
Everything goes fine except when I get to the part where you actually have to print the items onto the DOM.
I get this error:
Uncaught TypeError: undefined is not a function
Here is my code with a bunch of notes I left to show you how it works.
var minimize = function() {
$('.segment').each(function(){
var title_box = $(this).children('.title');
// Selects the container of the title.
var title = $(this).children('.title').text().trim();
// Takes the child title of the each .segment class and selects its innards.
console.log(title);
var res = title.split("");
// Splits the text into an array.
console.log(res);
var fragment = [];
// initializing the empty array
for (x = 0; x < 4; x++) {
fragment.push(res[x]);
console.log(fragment);
// Loops through to make sure it's not more than 5 characters long
};
var final = fragment.join("");
// Joins the broken up string together.
title_box.empty();
final.appendTo(title_box);
});
};
What do you think I did wrong? And if there's any other ways for me to make this code more efficient, then please don't hesitate to tell me.
Right here you define fragment as an array:
var fragment = [];
You then populate it and do this:
var final = fragment.join("");
Read the docs on array.join to understand what that function does. In short, it joins your array together into a string
So now when you do this:
final.appendTo(title_box);
You get your TypeError because string doesn't have an appendTo method
What you probably wanted was a jquery object to call appendTo on.
Perhaps you meant:
title_box.text(final);

Categories