Any idea why this will not push the TFW to the list. TFW is input from a text box that does work, but it will just not push it to the list.
I could not put the code in becuase StackOverflow was mad about how much code it was.
function tfw() {
var goodTrump = [
"america",
"americans",
"white people",
"african americans",
"black people",
"blacks",
"whites",
"latinos",
"latinas",
"mexicans",
"church",
"christianity",
"god",
"jesus",
"church and state",
"trump",
"money"
];
var badTrump = [
"mexico",
"immigration",
"muslims",
"islamic terrorist",
"terrorist",
"islam",
"democrats",
"dexter"
];
var sadTrump = [
"death",
"no money",
"abortion",
"public school system",
"public schools"
];
var done = [
];
var TFW = document.getElementById("TFW").value
for (i = 0; i < done.length; i++) {
console.log(done[i]);
}
if (TFW == "") {
document.getElementById("image").innerHTML = "<img src='http://inthesetimes.com/images/articles/trump_flicker_face_yess.jpg'><br> Cant react to something not there.";
} else if (badTrump.indexOf(TFW) !== -1) {
document.getElementById("image").innerHTML = "<img src='http://inthesetimes.com/images/articles/trump_flicker_face_yess.jpg'>";
} else if (goodTrump.indexOf(TFW) !== -1) {
document.getElementById("image").innerHTML = "<img src='http://noiimages.s3.amazonaws.com/images/redstate/20160614-1525871659.jpg'>";
} else if (sadTrump.indexOf(TFW) !== -1) {
document.getElementById("image").innerHTML = "<img src='http://www.mintpressnews.com/wp-content/uploads/2016/08/1033209603.jpg'>";
} else {
var failsafe = Math.floor(Math.random() * 3);
if (failsafe === 0) {
document.getElementById("image").innerHTML = "<img src='http://inthesetimes.com/images/articles/trump_flicker_face_yess.jpg'>";
goodTrump.push(TFW);
} else if (failsafe === 1) {
document.getElementById("image").innerHTML = "<img src='http://noiimages.s3.amazonaws.com/images/redstate/20160614-1525871659.jpg'>";
badTrump.push(TFW);
} else {
document.getElementById("image").innerHTML = "<img src='http://www.mintpressnews.com/wp-content/uploads/2016/08/1033209603.jpg'>";
sadTrump.push(TFW);
}
}
}
Any one know what the problem is?
You defined TFW with this code, but .value is not a function. If you log your value for TFW, it's probably undefined right now, which would be why you aren't able to push it to an array
You may be thinking of the jQuery function .val() which would return the content of the div with id TFW
var TFW = $("#TFW").val();
Alternatively, there is a pure javascript solution. If #TFW has no nested elements, you could use .innerHTML
var TFW = document.getElementById("TFW").innerHTML
Related
I have this mini CRUD in vanilla JS and HTML.
I need to be able to add or remove items and then list the array movies accordingly. I also need to do that without refreshing the page because of my hardcoded array.
I can't really call listMovies() every time a title is added or removed , otherwise I'd have multiple repetitions of the array displayed in the page.
Can anyone help me with a a solution for that?
This is my code:
window.onload = function () {
//Hard-coded array of movies - data.
// App is not connected to a database so everytime page is refreshed the array goes back to its original content.
var movies = [
'The Shawshank Redemption', 'The Godfather', 'Star Wars: Episode V - The Empire Strikes Back',
'Forrest Gump', 'The Perks of Being a Wallflower', 'The Dark Knight', 'Changeling', 'It\'s a Wonderful Life',
'The Silence of the Lambs', '8 Mile', 'The Breakfast Club', 'Django Unchained', 'Silver Linings Playbook',
'The Shining', 'Seven', 'American Beauty', 'Pulp Fiction', 'Zero Dark Thirty', 'Argo', 'The Hurt Locker'
];
// Variables for DOM manipulation
// var movieList = document.getElementById("movie-list__container");
var videoInput = document.getElementById("videoInput");
var addVideo = document.getElementById("addVideo");
var removeVideo = document.getElementById("removeVideo");
var alertMsg = document.getElementById("alertMsg");
var autocomplete = document.getElementById("autocomplete");
var searchResults = document.getElementById("search-results");
var movieListResults = document.getElementById("movie-list-results");
listMovies();
function listMovies() {
movies.sort();
for (i = 0; i < movies.length; i++) {
movieListResults.innerHTML += "<li>" + movies[i] + "</li>"
};
}
addVideo.onclick = addMovies;
function addMovies() {
var title = videoInput.value;
if (add(movies, title)) {
videoInput.value = "";
searchResults.innerHTML = '';
movieListResults.innerHTML += "<li>" + title + "</li>";
alertMsg.classList.remove("fail");
alertMsg.classList.add("success");
alertMsg.innerHTML = "Title was inserted successfully";
} else {
alertMsg.innerText = 'Please add a video title';
alertMsg.classList.remove("success");
alertMsg.classList.add("fail");
}
}
function add(data, title) {
if (title == "") {
return false;
} else {
data.push(title);
return true;
}
}
autocomplete.onkeyup = function () {
var results = [];
var userInput = this.value;
searchResults.innerHTML = "";
if (userInput != "") {
results = search(movies, userInput);
searchResults.style.display = "block";
if (results.length == 0) {
searchResults.innerHTML += "<li>Not found</li>";
searchResults.style.color = "grey";
} else {
searchResults.style.color = "black";
for (i = 0; i < results.length; i++) {
searchResults.innerHTML += "<li>" + results[i] + "</li>";
}
}
}
};
function search(data, input) {
var results = [];
for (i = 0; i < data.length; i++) {
if (input.toLowerCase() === data[i].slice(0, input.length).toLowerCase()) {
results.push(data[i]);
}
}
return results;
}
removeVideo.onclick = deleteMovie;
function deleteMovie() {
var title = videoInput.value;
if (title === "") {
alertMsg.innerHTML = 'Please enter the title you want to remove';
alertMsg.classList.add("fail");
} else {
if (remove(movies, title)) {
alertMsg.innerHTML = "Title has been successfully removed";
alertMsg.classList.add("success");
} else {
alertMsg.innerHTML = "Title not found";
alertMsg.classList.add("fail");
}
}
}
function remove(data, title) {
for (var i = 0; i < data.length; i++) {
if (title.toLowerCase() === data[i].toLowerCase()) {
data.splice(i, 1);
return true;
}
}
return false;
}
}; //End of window.onload
Nvm!
I figured it out by getting rid of the listMovies() and having the array printed once.
After that, I used a for loop for addMovie() and deleteMovie() to loop through the array and print it after the updates.
I realized that all I needed was to loop through the movies array and display the array again for both addMovie() and deleteMovie().
for (i = 0; i < movies.length; i++) {
movieListResults.innerHTML += "<li>" + movies[i] + "</li>"
};
My logic to add and remove titles in JS was correct but the logic to display the titles in HTML wasn't.
PS: FYI I'm a beginner!
Cheers
I have json data like this image, which I got from PHP.
and I want to access all data from json.
for my current case, I want to match existing data with data from Json.
but i got a little error. all of my data is not same with Json data.
Though there must be some data that is suitable.
this my code
const dataArr = <?= $ar; ?>;
console.log(dataArr); //image 1
var mySVG = document.getElementById("alphasvg");
var svgDoc;
mySVG.addEventListener("load",function() {
svgDoc = mySVG.contentDocument.documentElement;
var xd = svgDoc.getElementsByTagName("rect");
for(i=0;i<xd.length;i++){
let get_a = xd[i].getAttribute('id');
for(x = 1; x<= 30; x++){
for(y=0; y<=4; y++){
if(get_a == 'rect' + x + '_child' + y){
//console.log(get_a); //img2
if(dataArr[(x-1)*y].idval.includes(get_a) == true){
console.log('yes u good');
} else {
console.log('error');
}
}
}
}
}
}, false);
can somone help me?
edit : resut of console.log(get_a,dataArr[(x-1)*y]);
my data is not matching.
If you simply want to search the objects inside the array for a particular occurence of a key - idval - and it's value you can use a simple for-loop like:
for (var a = 0; a < dataArr.length; a++) {
if (dataArr[a].idval == get_a) {
console.log("there it is", dataArr[a]);
break;
}
}
Here's an example:
var dataArr = [{
id: "test",
lantai: 1,
status_asrama: "tersedia",
idval: "rect_child1"
},
{
id: "anothertest",
lantai: 2,
status_asrama: "tersedia",
idval: "rect_child2"
}, {
id: "finaltest",
lantai: 3,
status_asrama: "tersedia",
idval: "rect_child3"
}
];
let get_a = "rect_child2";
for (var a = 0; a < dataArr.length; a++) {
if (dataArr[a].idval == get_a) {
console.log("there it is", dataArr[a]);
break;
}
}
I can convert JSON to HTML using JsontoHtml library. Now,I need to convert present HTML to JSON as shown in this site. When looked into the code I found the following script:
<script>
$(function(){
//HTML to JSON
$('#btn-render-json').click(function() {
//Set html output
$('#html-output').html( $('#html-input').val() );
//Process to JSON and format it for consumption
$('#html-json').html( FormatJSON(toTransform($('#html-output').children())) );
});
});
//Convert obj or array to transform
function toTransform(obj) {
var json;
if( obj.length > 1 )
{
json = [];
for(var i = 0; i < obj.length; i++)
json[json.length++] = ObjToTransform(obj[i]);
} else
json = ObjToTransform(obj);
return(json);
}
//Convert obj to transform
function ObjToTransform(obj)
{
//Get the DOM element
var el = $(obj).get(0);
//Add the tag element
var json = {'tag':el.nodeName.toLowerCase()};
for (var attr, i=0, attrs=el.attributes, l=attrs.length; i<l; i++){
attr = attrs[i];
json[attr.nodeName] = attr.value;
}
var children = $(obj).children();
if( children.length > 0 ) json['children'] = [];
else json['html'] = $(obj).text();
//Add the children
for(var c = 0; c < children.length; c++)
json['children'][json['children'].length++] = toTransform(children[c]);
return(json);
}
//Format JSON (with indents)
function FormatJSON(oData, sIndent) {
if (arguments.length < 2) {
var sIndent = "";
}
var sIndentStyle = " ";
var sDataType = RealTypeOf(oData);
// open object
if (sDataType == "array") {
if (oData.length == 0) {
return "[]";
}
var sHTML = "[";
} else {
var iCount = 0;
$.each(oData, function() {
iCount++;
return;
});
if (iCount == 0) { // object is empty
return "{}";
}
var sHTML = "{";
}
// loop through items
var iCount = 0;
$.each(oData, function(sKey, vValue) {
if (iCount > 0) {
sHTML += ",";
}
if (sDataType == "array") {
sHTML += ("\n" + sIndent + sIndentStyle);
} else {
sHTML += ("\"" + sKey + "\"" + ":");
}
// display relevant data type
switch (RealTypeOf(vValue)) {
case "array":
case "object":
sHTML += FormatJSON(vValue, (sIndent + sIndentStyle));
break;
case "boolean":
case "number":
sHTML += vValue.toString();
break;
case "null":
sHTML += "null";
break;
case "string":
sHTML += ("\"" + vValue + "\"");
break;
default:
sHTML += ("TYPEOF: " + typeof(vValue));
}
// loop
iCount++;
});
// close object
if (sDataType == "array") {
sHTML += ("\n" + sIndent + "]");
} else {
sHTML += ("}");
}
// return
return sHTML;
}
//Get the type of the obj (can replace by jquery type)
function RealTypeOf(v) {
if (typeof(v) == "object") {
if (v === null) return "null";
if (v.constructor == (new Array).constructor) return "array";
if (v.constructor == (new Date).constructor) return "date";
if (v.constructor == (new RegExp).constructor) return "regex";
return "object";
}
return typeof(v);
}
</script>
Now, I am in need of using the following function in PHP. I can get the HTML data. All what I needed now is to convert the JavaScript function to PHP function. Is this possible? My major doubts are as follows:
The primary input for the Javascript function toTransform() is an object. Is it possible to convert HTML to object via PHP?
Are all the functions present in this particular JavaScript available in PHP?
Please suggest me the idea.
When I tried to convert script tag to json as per the answer given, I get errors. When I tried it in json2html site, it showed like this: .. How to achieve the same solution?
If you are able to obtain a DOMDocument object representing your HTML, then you just need to traverse it recursively and construct the data structure that you want.
Converting your HTML document into a DOMDocument should be as simple as this:
function html_to_obj($html) {
$dom = new DOMDocument();
$dom->loadHTML($html);
return element_to_obj($dom->documentElement);
}
Then, a simple traversal of $dom->documentElement which gives the kind of structure you described could look like this:
function element_to_obj($element) {
$obj = array( "tag" => $element->tagName );
foreach ($element->attributes as $attribute) {
$obj[$attribute->name] = $attribute->value;
}
foreach ($element->childNodes as $subElement) {
if ($subElement->nodeType == XML_TEXT_NODE) {
$obj["html"] = $subElement->wholeText;
}
else {
$obj["children"][] = element_to_obj($subElement);
}
}
return $obj;
}
Test case
$html = <<<EOF
<!DOCTYPE html>
<html lang="en">
<head>
<title> This is a test </title>
</head>
<body>
<h1> Is this working? </h1>
<ul>
<li> Yes </li>
<li> No </li>
</ul>
</body>
</html>
EOF;
header("Content-Type: text/plain");
echo json_encode(html_to_obj($html), JSON_PRETTY_PRINT);
Output
{
"tag": "html",
"lang": "en",
"children": [
{
"tag": "head",
"children": [
{
"tag": "title",
"html": " This is a test "
}
]
},
{
"tag": "body",
"html": " \n ",
"children": [
{
"tag": "h1",
"html": " Is this working? "
},
{
"tag": "ul",
"children": [
{
"tag": "li",
"html": " Yes "
},
{
"tag": "li",
"html": " No "
}
],
"html": "\n "
}
]
}
]
}
Answer to updated question
The solution proposed above does not work with the <script> element, because it is parsed not as a DOMText, but as a DOMCharacterData object. This is because the DOM extension in PHP is based on libxml2, which parses your HTML as HTML 4.0, and in HTML 4.0 the content of <script> is of type CDATA and not #PCDATA.
You have two solutions for this problem.
The simple but not very robust solution would be to add the LIBXML_NOCDATA flag to DOMDocument::loadHTML. (I am not actually 100% sure whether this works for the HTML parser.)
The more difficult but, in my opinion, better solution, is to add an additonal test when you are testing $subElement->nodeType before the recursion. The recursive function would become:
function element_to_obj($element) {
echo $element->tagName, "\n";
$obj = array( "tag" => $element->tagName );
foreach ($element->attributes as $attribute) {
$obj[$attribute->name] = $attribute->value;
}
foreach ($element->childNodes as $subElement) {
if ($subElement->nodeType == XML_TEXT_NODE) {
$obj["html"] = $subElement->wholeText;
}
elseif ($subElement->nodeType == XML_CDATA_SECTION_NODE) {
$obj["html"] = $subElement->data;
}
else {
$obj["children"][] = element_to_obj($subElement);
}
}
return $obj;
}
If you hit on another bug of this type, the first thing you should do is check the type of node $subElement is, because there exists many other possibilities my short example function did not deal with.
Additionally, you will notice that libxml2 has to fix mistakes in your HTML in order to be able to build a DOM for it. This is why an <html> and a <head> elements will appear even if you don't specify them. You can avoid this by using the LIBXML_HTML_NOIMPLIED flag.
Test case with script
$html = <<<EOF
<script type="text/javascript">
alert('hi');
</script>
EOF;
header("Content-Type: text/plain");
echo json_encode(html_to_obj($html), JSON_PRETTY_PRINT);
Output
{
"tag": "html",
"children": [
{
"tag": "head",
"children": [
{
"tag": "script",
"type": "text\/javascript",
"html": "\n alert('hi');\n "
}
]
}
]
}
I assume that your html string is stored in $html variable. So you should do:
$dom = new DOMDocument();
$dom->loadHTML($html);
foreach($dom->getElementsByTagName('*') as $el){
$result[] = ["type" => $el->tagName, "value" => $el->nodeValue];
}
$json = json_encode($result, JSON_UNESCAPED_UNICODE);
Note: This algorithm doesn't support parent-child tags and fetch all tags as parent elements and parses all of them in a sorted queue. Of course, you can implement this feature by studying the DOMDocument classes features.
I wrote this to convert HTML Form tags to a JSON object. You may be able to build off of this.
class HtmlToJson {
public $html;
public $filter;
function __construct($html, $filter) {
$this->dom = new DOMDocument();
$this->dom->loadHTML( $html );
$this->jsonObj = array('form_tag_attrs'=>array(), 'form_values'=>array());
$this->filter = $filter;
}
function recursivePair($element, $tagName) {
if ( isset( $element->attributes ) ) {
$nameAttr = $element->getAttribute('name');
if ($nameAttr) {
$this->jsonObj['form_values'][$nameAttr] = $element->getAttribute('value');
}
if ($element->nodeName === $tagName) {
foreach ( $element->attributes as $attribute ) {
$this->jsonObj['form_tag_attrs'][ $attribute->name ] = $attribute->value;
}
}
}
if ( isset( $element->childNodes ) ) {
foreach ( $element->childNodes as $subElement ) {
$this->recursivePair( $subElement, $tagName );
}
}
}
function json() {
$element = ($this->filter ? $this->dom->getElementsByTagName($this->filter)->item(0) : $this->dom->documentElement);
$this->recursivePair($element, $this->filter);
return $this->jsonObj;
}
}
$formJson = new HtmlToJson($curlResult, 'form');
echo json_encode($formJson->json());
I'm currently writing a program that uses ";" as a seperator and extracts the url up until that point upon searching the content.
So it has the format:
name;surname
In searching the given arrays... I decided to go the extra mile and test for arrays without the ";" but this has confused the program - it has no idea of the ";" position anymore and this throws a spanner in the works!
Here is my code so far - many thanks in advance!
pages =
[
"The first", "An;alternative;page", "Yet another page"
]
u_c_pages =
[
"www.cam.ac.uk;"+pages[0]
,
"www.warwick.ac.uk"+pages[1]
,
"www.kcl.ac.uk;"+pages[1]
,
"www;"+pages[2]
]
var pattern5 = prompt('5) Please enter a search term:');
function url1_m1(u_c_pages,pattern)
{
var seperator = [];
var seperatorPos = [];
if(pattern)
{
for (var i = 0; i < u_c_pages.length; i++)
{
var found = true;
if((u_c_pages[i].indexOf(";"))<0)
{
found=false;
}
else
{
seperator[seperator.length] = i;
seperatorPos[seperatorPos.length] = (u_c_pages[i].indexOf("|"));
}
}
if(seperator.length==0)
{
return("Nothing found!");
}
else
var found2 = "";
{
for (var j = 0; j < seperator.length; j++)
{
if(u_c_pages[j].substring(seperatorPos[j],u_c_pages[j].length-1).toLowerCase().indexOf(pattern.toLowerCase()) >= 0)
{
found2 = (u_c_pages[j].substring(0,seperatorPos[j]));
break;
}
}
return(found2)
}
}
else
{
// only returned when the user decides to type in nothing
return("Nothing entered!");
}
}
alert(url1_m1(u_c_pages,pattern5));
enjoy the power of regex:
on JSFiddle
pages = ["The first", "An;alternative;page", "Yet another page"];
u_c_pages = [
"www.lboro.ac.uk;"+pages[0],
"www.xyz.ac.uk;"+pages[1],
"www.xyz.ac.uk;"+pages[1],
"www;"+pages[2]
];
var pattern5 = prompt('5) Please enter a search term:');
function url1_m1(u_c_pages,pattern)
{
// escape search pattern
pattern = pattern.toLowerCase().replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
pattern = new RegExp('^([^;]+);.*?' + pattern, 'i');
var result = null;
for(var i=0;i<u_c_pages.length;i++) {
if((result = u_c_pages[i].match(pattern))) {
return result[1];
}
}
return false;
}
alert(url1_m1(u_c_pages,pattern5));
You can use String.split(";") to split a string into segments. The parameter is the seperator.
This question already has answers here:
Loop (for each) over an array in JavaScript
(40 answers)
Closed 5 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I have the following JSON structure:
[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]
How do I iterate over it using JavaScript?
var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "class": "child-of-10"}];
for (var i = 0; i < arr.length; i++){
document.write("<br><br>array index: " + i);
var obj = arr[i];
for (var key in obj){
var value = obj[key];
document.write("<br> - " + key + ": " + value);
}
}
note: the for-in method is cool for simple objects. Not very smart to use with DOM object.
Taken from jQuery docs:
var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(arr, function() {
$("#" + this).text("My id is " + this + ".");
return (this != "four"); // will stop running to skip "five"
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
Use for...of:
var mycars = [{name:'Susita'}, {name:'BMW'}];
for (var car of mycars)
{
document.write(car.name + "<br />");
}
Result:
Susita
BMW
Please let me know if it is not easy:
var jsonObject = {
name: 'Amit Kumar',
Age: '27'
};
for (var prop in jsonObject) {
alert("Key:" + prop);
alert("Value:" + jsonObject[prop]);
}
If this is your dataArray:
var dataArray = [{"id":28,"class":"Sweden"}, {"id":56,"class":"USA"}, {"id":89,"class":"England"}];
then:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var CLASS = this.class;
});
Copied and pasted from http://www.w3schools.com, there is no need for the JQuery overhead.
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x];
}
RESULT: John Doe 25
mootools example:
var ret = JSON.decode(jsonstr);
ret.each(function(item){
alert(item.id+'_'+item.classd);
});
You can use a mini library like objx - http://objx.googlecode.com/
You can write code like this:
var data = [ {"id":"10", "class": "child-of-9"},
{"id":"11", "class": "child-of-10"}];
// alert all IDs
objx(data).each(function(item) { alert(item.id) });
// get all IDs into a new array
var ids = objx(data).collect("id").obj();
// group by class
var grouped = objx(data).group(function(item){ return item.class; }).obj()
There are more 'plugins' available to let you handle data like this, see http://code.google.com/p/objx-plugins/wiki/PluginLibrary
With nested objects, it can be retrieve as by recursive function:
function inside(events)
{
for (i in events) {
if (typeof events[i] === 'object')
inside(events[i]);
else
alert(events[i]);
}
}
inside(events);
where as events is json object.
Marquis Wang's may well be the best answer when using jQuery.
Here is something quite similar in pure JavaScript, using JavaScript's forEach method. forEach takes a function as an argument. That function will then be called for each item in the array, with said item as the argument.
Short and easy:
var results = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"} ];
results.forEach(function(item) {
console.log(item);
});
this is a pure commented JavaScript example.
<script language="JavaScript" type="text/javascript">
function iterate_json(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
hr.open("GET", "json-note.php", true);//this is your php file containing json
hr.setRequestHeader("Content-type", "application/json", true);
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
var results = document.getElementById("myDiv");//myDiv is the div id
for (var obj in data){
results.innerHTML += data[obj].id+ "is"+data[obj].class + "<br/>";
}
}
}
hr.send(null);
}
</script>
<script language="JavaScript" type="text/javascript">iterate_json();</script>// call function here
var jsonString = `{
"schema": {
"title": "User Feedback",
"description": "so",
"type": "object",
"properties": {
"name": {
"type": "string"
}
}
},
"options": {
"form": {
"attributes": {},
"buttons": {
"submit": {
"title": "It",
"click": "function(){alert('hello');}"
}
}
}
}
}`;
var jsonData = JSON.parse(jsonString);
function Iterate(data)
{
jQuery.each(data, function (index, value) {
if (typeof value == 'object') {
alert("Object " + index);
Iterate(value);
}
else {
alert(index + " : " + value);
}
});
}
Iterate(jsonData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Another solution to navigate through the JSON document is JSONiq (implemented in the Zorba engine), where you can write something like this:
let $doc := [
{"id":"10", "class": "child-of-9"},
{"id":"11", "class": "child-of-10"}
]
for $entry in members($doc) (: binds $entry to each object in turn :)
return $entry.class (: gets the value associated with "class" :)
You can run it on http://public.rumbledb.org:9090/public.html