XML file in Javascript, getElementByAttribute - javascript

Let's suppose I have an XML file like this:
<?xml version="1.0" encoding="ISO-8859-1"?>
<MIDIFile>
<Event>
<Absolute>0</Absolute>
<NoteOn Channel="1" Note="40" Velocity="64"/>
</Event>
<Event>
<Absolute>236</Absolute>
<NoteOff Channel="1" Note="40" Velocity="0"/>
</Event>
</MIDIFile>
Thanks to some great tutorial I now know how to get these values in my javascript.
For example, I can iterate thru all the "Events" tag and get the "Absolute" value like this:
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","test.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
// make an array with all the events from the xml file
var events = xmlDoc.getElementsByTagName("Event")
for (var i = 0; i<events.length; i++)
console.log(events[i].getElementsByTagName("Absolute")[0].childNodes[0].nodeValue)
this will return
0
236
Now, how the hell can I access the "NoteOn" attribute and get its values? I want to iterate thru all the Events in the XML, see if they contains NoteOn or NoteOff and load an array with all the notes, their duration, velocity and channels.
Please help me! getElementsByTagName("NoteOn") just doesn't work... If it might help, here are some screenshot of what happens if I console.log(xmlDoc)
Thanks a lot in advance!
edit in response to an answer. As I try to do this:
var noteon = xmlDoc.getElementsByTagName('noteon');
console.log(noteon)
the result is just this one
[]
re-edit:
If I write "NoteOn" instead of "noteon" it works!

var noteon = xmlDoc.getElementsByTagName('noteon');
var note = new Array;
for(var i = 0; i < noteon.length; i++){
note[i] = noteon[i].getAttribute('Note'); // or any of the attributes you want to get
}
Edit:
If noteon = [] then you have 2 options you can put the whole thing in a try catch, not the best thing to do in javascript, or you can put it in an if statement. Something like this should work:
var noteon = xmlDoc.getElementsByTagName('noteon');
var noteoff = xmlDoc.getElementsByTagName('noteoff');
var note = new Array;
if(noteon != []){
for(var i = 0; i < noteon.length; i++){
note[i] = noteon[i].getAttribute('Note'); // or any of the attributes you want to get
} else if(noteoff != []){
for(var i = 0; i < noteoff.length; i++){
note[i] = noteoff[i].getAttribute('Note'); // or any of the attributes you want to get
} else{
return; //makes sure the function returns to the call even if nothing was found
}
}

Related

Search For Text in Div

I'm trying to make a runnable console command through Chrome that searches for the word "takeID", and then grabs the content immediately after it between = and & from a div class.
What I have so far doesn't work because I'm very bad at JS so any help would be appreciated. Below is what I have so far:
var iframe=document.getElementsByClassName("activity activity-container-html5");
var searchValue = "takeID";
for(var i=0;i<iframe.length;i++){ if(iframe[i].innerHTML.indexOf(searchValue)>-1){}};
var subString = iframe.substring( iframe.lastIndexOf("=")+1, iframe.lastIndexOf("&"));
console.log(searchValue+"="+subString);
An example of the div class it would be searching would look like:
<div class="activity activity-container-html5" config="{example text;takeID=cd251erwera34a&more example text}">
There are two issues with the code. The first issue is the searchValue posts to the console as whatever is in between the takeID, and not the actual result from searching. The second issue is that the code to search between = and & doesn't work at all and I don't know why. What is wrong with the code?
I just want an output that would post to the log or a popup window saying:
takeID=cd251erwera34a
EDIT:
Something else I thought of was how would you be able to just parse the div and then search for what is in between "takeID=" and "&"? I tried this but I was getting the error "Uncaught TypeError: iframe.lastIndexOf is not a function".
var iframe=document.getElementsByClassName("activity activity-container-html5");
var subString = iframe.substring( iframe.lastIndexOf("takeId=") + 1, iframe.lastIndexOf("&") );
console.log(subString);
I looked this up and I see this is because what it is trying to process is not a string but I'm not sure why that is or how to fix it.
I don't know about you but the best would be to use json directly inside the html tag like this:
<div class="activity activity-container-html5" config="{'example':'text', 'takeID':'cd251erwera34a', 'other':''}">
Or use an array and check manually if the one you are checking is the one you want, like this:
function config(element, searchValue) {
if (element.hasAttribute('config')) {
var configData = JSON.parse(element.getAttribute('config'));
var res = "";
for (var i = 0; i < configData.length; i++) {
if (configData[i].includes(searchValue)) {
res = configData[i];
break;
}
}
return res;
}
}
el = document.getElementsByClassName('activity activity-container-html5');
for (var i = 0; i < el.length; i++) {
console.log(config(el[i], "takeID"));
}
<div class="activity activity-container-html5" config='["example=text", "takeID=cd251erwera34a", "othertext=here"]'>
The array-type (second example) is most likely to work better than the simple json one (first one).
I figured out what I needed to do. Below is working code:
var iframe=document.getElementsByClassName("activity activity-container-html5");
var div = "";
for(var i=0;i < iframe.length; i++){
div += (iframe[i].outerHTML);
}
var take = /takeID=([a-z0-9]*)&/;
var capture = div.match(take);
var matchID = capture[1];
console.log(matchID);
window.alert("takeID=" + matchID);

Show value of variable from json string

I have a for-loop:
var player = 5;
for (var i = 0; i <10; i++) {
$("#id").append('<div class="game_content_text">'+json_var[i].content+'</div>');
}
The json looks like:
"content":"<script>player</script>"
Now I only want to to write down the 5 but nothing is showing...
Edit: I simplified it. Why I have to show more code? The problem is in this lines...
For example if i show a simple text from the json ("content":"example!") it works...
For explanation:
I have a buck of personal questions in the JSON Feed.
Example: "Hello 'name_variable' how are you?"
And in the the 'name_variable' i want show random names...
If we append script tag dynamically then you need to call that code which is inside newly added script.
A script tag result cannot be assign a variable or it cannot be shown as result.
You can try following example
$(function(){
var test = "this.Foo = function() {alert('hi');}";
var F=new Function (test);
(new F()).Foo(); //Shows "Hi" alert
});
I'd like to get more code simply for the fact that I can understand the context better, because your code is rather confusing.
So apparently you try to display the value player in all your appended elements?
var player = 5;
for (var i = 0, l = json_var.length; i < l; i++) {
$("#id").append('<div class="game_content_text">' + player + '</div>');
}
Otherwise, if you really need that script to be stored in the json (for some reason). I'm assuming the class "game_content_text" is only used for this.
var player = 5;
for (var i = 0, l = json_var.length; i < l; i++) {
$("#id").append('<div class="game_content_text">' + json_var[i].content + '</div>');
}
"content": "<script>$('.game_content_text').append(player);</script>"
I'm not all that familiar with jQuery, but that should work.
Also, I really do not recommend this.

How do I reformat and output a javascript string into array?

Still learning... again sorry if this sounds stupid:
I have 2 variables "timestamps" and "clicks" and a string of numbers:
var myData = {
"timestamps":[
1362096000000,1362355200000,1362441600000,1362528000000
],
"clicks":[
[
1,2,3,4
]
};
I'm trying to restructure that into an array in this format:
[1362096000000,1],
[1362355200000,2],
[1362441600000,3],
[1362528000000,4],
Here is what I have so far: http://jsfiddle.net/3UsP6/1/
Javascript:
var myData = {"timestamps":[1369008000,1369094400,1369180800,],"clicks":[1,2,3,]};
var output = test;
for (var i = 0, l = myData.timestamps.length; i < l; i++)
{
output.push([myData.timestamps[i], myData.clicks[i]]);
}
HTML:
<body onload="javascript:alterText()">
<a id="test"></a>
</body>
I need to output the variable into the body of the page but I can't get it to display. What am I doing wrong?
Before anything else, if you are debugging, you are better off using the debugger of the browser (F12 in most browsers). Use console.log() to output to the console to see values. Breakpoints would be better since they pause code, and you can inspect values at that moment.
Now, for the mistakes you made:
Your output is test which is an <a>. You can't do a push since that's not an array. What you can do is create an array, fill it with values, and do a JSON.stringify to turn it into a string.
You should use document.get* functions, like document.getElementId() to refer to DOM elements. Though browsers do expose globals for elements with ids, you should avoid that.
This should fix it:
function alterText() {
var myData = {
"timestamps": [1369008000, 1369094400, 1369180800],
"clicks": [1, 2, 3]
};
var output = [];
var link = document.getElementById('test');
for (var i = 0, l = myData.timestamps.length; i < l; i++) {
output.push([myData.timestamps[i], myData.clicks[i]]);
}
// Output to console
console.log(output);
// Convert array to text and output to element
link.innerHTML = JSON.stringify(output);
}
A big problem with the jFiddle is you don't include jQuery. When trying to get an element by id, you cannot just reference it by name. Below is a revised version that does output what you want (though not in a nice format or anything).
$(function() {
var myData = {"timestamps":[1369008000,1369094400,1369180800,],"clicks":[1,2,3,]};
var output = $('#test');
for (var i = 0; i < myData.timestamps.length; i++) {
output.append([myData.timestamps[i], myData.clicks[i]]);
}
});

get only the node inside another one in javascript

Here's my XML
<?xml version="1.0" encoding="ISO-8859-1" ?>
<book>
<title>My Title</title>
<description></description>
<chapter>
<title>Chapter 1</title>
<description>text inside chapter</description>
</chapter>
</book>
So I try to get information INSIDE the <chapter> tag
here's my code :
function afficheTitres(doc) {
Items = doc.getElementsByTagName("chapter");
elementol = document.createElement("ol");
var longueur = Items.length;
for ( k = 0; k < longueur ; ++k) {
elementli = document.createElement("li");
x=doc.getElementsByTagName("title")[k];
var longueurtitre = x.length;
y=x.childNodes[0];
txt=y.nodeValue;
test = document.createTextNode(txt)
elementli.appendChild( test);
elementretour = document.createElement('br');
elementli.appendChild( elementretour
);
descript=doc.getElementsByTagName("description")[k];
descriptNode=descript.childNodes[0];
txt2=descriptNode.nodeValue;
test2 = document.createTextNode(txt2)
elementli.appendChild( test2);
elementol.appendChild(elementli);
}
body = document.getElementsByTagName("body").item(0);
body.appendChild(elementol);
}
The problem is that these lines :
x=doc.getElementsByTagName("title")[k];
and
descript=doc.getElementsByTagName("description")[k];
get information coming from the "BOOK" section not from the chapter.
I'm sure someone knows how to get this.
thanks
In your code you use doc variable which appears to be something inherited from document object, see the reference.
The .getElementsByTagName("title") method returns an array of tags title which appears not just in the chapter, but also in the root element, book.
Search from chapter node, not from doc
var chapters = doc.getElementsByTagName("chapter");
for(var i=0; i<chapters.length; ++i) {
// search from book, which is what you don't want
// doc.getElementsByTagName("title")[0];
// search from chapter, you want this
chapters[i].getElementsByTagName("title")[0];
}
Note
In newer browsers (IE8+) you can save yourself lots of pain if you use .querySelectorAll() method (which btw renders great portion of jQuery obsolete).
var titles = doc.querySelectorAll("chapter title");
alert(titles[0].innerHTML); // Chapter 1
Have you tried getting the collection of chapters first:
var chapters =doc.getElementsByTagName("chapter");
And then iterating through each chapter to find the child nodes of that instance in the collection?
if (chapters.length > 0)
{
for (i = 0; i < resultList.length; i++)
{
var title = chapters[i].getElementsByTagName("title")[0];
var desc = chapters[i].getElementsByTagName("description")[0];
// do work here
}
}

MVC: Iterating a Viewbag array in javascript

The goal is to get the data from the ViewBag.Array to a Javascript array. The data is calculated in the controller so I cannot fetch it straight from the database. I need the data to draw a chart with jqplot. Code:
for(i = 0; i < #ViewBag.Array.Length; i++)
{
jScriptArray[i] = #ViewBag.Array[i];
}
The problem is "'i' does not exist in the current context" in the #ViewBag.Array[i] but has no problems in the jScriptArray[i]. Any help is appreciated.
You may try the following:
var array = #Html.Raw(Json.Encode(#ViewBag.Array));
for(var i = 0; i < array.length; i++) {
jScriptArray[i] = array[i];
}
var array=#Html.Raw(JsonConvert.SerializeObject(ViewBag.Array));
you can make use of JsonConvert.SerializeObject
Hope this Helps.
<script>
var jScriptArray=[];
#{
for(i = 0; i < ViewBag.Array.Length; i++){
<text>jScriptArray[#i] = "#ViewBag.Array[#i]";</text>
i++;
}
}
</script>
You will end up with something like this in html file:
jScriptArray[0] = "ArrayValue0";
jScriptArray[1] = "ArrayValue1";
jScriptArray[2] = "ArrayValue2";
The best way to achieve your goal is to create a JSON controller that returns the data into a JSON array.
From your javascript you can request the data and then process it.
Hope this helps

Categories

Resources