I've searching and trying other suggestions in StackOverflow.
Unfortunately the answers are not working for me. They are suggesting to use 'foreach' instead of 'for', but how could I... if I want to iterate just 50 times? :<
Well, I'll just paste the code and let's see if some good folk can help me.
JSLint was unable to finish.
Unexpected 'for'. for (var i=1;i<=50;i+=1){
line 6 column 8
Unexpected 'var'. for (var i=1;i<=50;i+=1){
line 6 column 13
"use strict";
var campo = [];
var ronda = 0;
// Llenamos el campo de 50 humanos/maquinas/extraterrestres = 150 jugadores
for (var i=1;i<=50;i+=1){
campo.push(new Human("h"+i));
campo.push(new Machine("m"+i));
campo.push(new Alien("e"+i));
}
// Array.prototype.suffle para barajar el Array
Array.prototype.shuffle = function() {
var input = this;
for (var i=input.length-1;i>=0;i-=1){
var randomIndex = Math.floor(Math.random()*(i+1));
var itemAtIndex = input[randomIndex];
input[randomIndex]=input[i];
input[i] = itemAtIndex;
}
};
// Barajamos el Array campo
campo.shuffle();
// Comprobamos que quedan más de 1 jugador por ronda
while (campo.length>1) {
console.log("Iniciando ronda: " + ++ronda);
console.log(campo.length + " jugadores luchando.");
// Recorremos el campo, y luchamos
var muertos = 0;
for (var i=0; i<campo.length-1; i+=2){
// Caso de numero impar de jugadores:
// Por ejemplo cuando solo quedan 3 jugadores. Pelean 1 vs 2. El 3 se libra.
// - Si siguen vivos y aguantan otra ronda, se barajan las posiciones otra vez y
// vuelven a pelear dos. Y el nuevo tercero no pelea.
// - Si uno de los dos muere, en la siguiente ronda ya solo quedan 2, y pelean normal.
campo[i].fight(campo[(i+1)]);
// # descomentar solo la siguiente linea para hacer comprobaciones #
// console.log("["+ campo[i].username + "] VS ["+ campo[(i+1)].username + "]");
if (campo[i].health<=0) {
console.log("El " + campo[i].constructor.name + " llamado " + campo[i].showName() + " ha sido asesinado :<");
var fallecido = campo.splice(i, 1);
// # descomentar solo la siguiente linea para hacer comprobaciones #
//console.log(fallecido[0]);
i--; // como el array se hace pequeño, hay que corregir el error para que no se salte jugadores
muertos++;
} else {
if (campo[(i+1)].health<=0) {
console.log("El " + campo[(i+1)].constructor.name + " llamado " + campo[(i+1)].showName() + " ha sido asesinado :<");
var fallecido = campo.splice((i+1), 1);
// # descomentar solo la siguiente linea para hacer comprobaciones #
// console.log(fallecido[0]);
i--; // como el array se hace pequeño, hay que corregir el error para que no se salte jugadores
muertos++;
}
else {
// # descomentar solo la siguiente linea para hacer comprobaciones #
// console.log("Siguen vivos");
}
}
}
console.log("Fin de ronda!")
if (muertos === 1) {
console.log("Ha muerto " + muertos + " jugador.");
} else {
console.log("Han muerto " + muertos + " jugadores.");
}
// Al final de la ronda barajamos de nuevo
campo.shuffle();
}
if (campo.length === 1) {
console.log("Vaya!! Ha sido una memorable batalla!");
console.log("Después de tantos bits derramados y de " + ronda + " rondas... el jugador '" + campo[0].constructor.name + "' llamado '" + campo[0].showName() + "' se ha alzado con la victoria!!");
}
There are some other for in the code, but It seems to stop at the first one.
Thank you in advance!
Forgot to say, the code works PERFECT. But I was just validating it with JSLint, also 'tolerating' for warnings in JSLint doesn't work.
When you choose to tolerate for, the next thing it's warning you about is the global declaration of the var i. Since you've got the for-loop at the top-level, i becomes available everywhere in your program.
I'd just tolerate for and wrap it up an in IIFE. That way, i is only available inside this function, and doesn't leak out to the global scope.
(function() {
var i = 0;
for (i=1;i<=50;i+=1) {
campo.push(new Human("h"+i));
campo.push(new Machine("m"+i));
campo.push(new Alien("e"+i));
}
})();
You could also, barring using an existing implementation out there, create a function that generalizes the "repeat n times" definition.
function repeat(fn, n) {
var i = 0;
for (;i < n; i += 1) {
fn();
}
}
Use in your case would look like:
function initialize() {
campo.push(new Human("h"+i));
campo.push(new Machine("m"+i));
campo.push(new Alien("e"+i));
}
// then later
repeat(initialize, 50);
jslint is being overzealous (some would say), it expects all var statements to be at the top of a function.
You can tell jslint that you don't care about that rule by adding an instruction comment on the line above where you are declaring the variable.
// Llenamos el campo de 50 humanos/maquinas/extraterrestres = 150 jugadores
/*jslint for:true */
for (var i=1;i<=50;i+=1){
Or you can move all your var i; to the top of the file/function
Related
I had another post with my project (container bound script) but this time I've tried to do the other way when I modify a Google Doc table section (when I tick in column J) it will modify the line in the Google Sheet because each line corresponds to a Google Doc project. It's the column J; I set a trigger to view the Google Doc in the same window and I can modify inside the thing is that when I close the Google Doc it's not modifying instantly the line of the Google Sheet.If I tick another time ; this is the one moment it modifies the line so the problem is that it has a delay of a tick. To see it :
1) log google make copy Tools -> Script editor set trigget view_doc_and_edit -> from spreadsheet on edit >>>
2) now if you click for a doc in the colum J you can see the google doc corresponding and we can modify it
3) we close we look in the table nothing changed and if we click another time the same place(row) it will change the row.
I know that for the Google Doc onEdit doesn't exist and I've tried to do by this way any idea is welcomed to modify in the same time to have an interactive tool
This is my project
https://docs.google.com/spreadsheets/d/1k_kj98U__0Bk44gh0qRFpaVx0ru3sN1pSPGiMQwimxo/edit?usp=sharing
var TITLE = 'Show Google Doc';
var SPREADSHEET_ID = "1k_kj98U__0Bk44gh0qRFpaVx0ru3sN1pSPGiMQwimxo"; // = assign your spreadsheet id to this variable
var column_name_project ;
var column_code_project ;
var column_chef_project;
var column_service ;
var column_other_services ;
var column_type_of_project ;
var column_perimeter ;
var column_date_project ;
var COLUMN_URL ;
/** will return the number of the column correspondant **/
function find_columns_in_projet(){
var tss = SpreadsheetApp.openById(SPREADSHEET_ID);
var sheet = tss.getSheets()[0];
var lastColumn = sheet.getLastColumn();
var data = sheet.getRange(1,1,1,lastColumn).getValues()[0];
for(var n=0;n<data.length;n++){
if(data[n].toString().indexOf('Name project') > -1)
column_name_project = n+1;
else if(data[n].toString().indexOf('Code') > -1)
column_code_project = n + 1;
else if(data[n].toString().indexOf('Chef') > -1)
column_chef_project= n + 1;
else if(data[n].toString().indexOf('Service') > -1)
column_service = n +1 ;
else if(data[n].toString().indexOf('Other services') > -1)
column_other_services = n + 1;
else if(data[n].toString().indexOf('Type of the project') > -1)
column_type_of_project = n + 1;
else if(data[n].toString().indexOf('Perimeter') > -1)
column_perimeter = n + 1;
else if(data[n].toString().indexOf('Date') > -1)
column_date_project = n + 1;
else if(data[n].toString().indexOf('URL') > -1)
COLUMN_URL = n +1 ;
}
}
/** pour visualiser le document sur la meme page **/
function view_doc_and_edit(event) {
find_columns_in_projet();
Logger.log("!! La colonne URL est: !!" + COLUMN_URL );
if( ( event.range.getSheet().getName() === "Sheet1" ) && ( event.range.getColumnIndex() == COLUMN_URL +1 ) ) {
if( event.value === "TRUE" ) {
try {
var URL = event.range.offset(0,-1,1,1).getValue();
Logger.log('The URL is : ' + URL );
var google_doc = DocumentApp.openByUrl(URL) ;
var body = google_doc.getBody();
Logger.log('The body is ' + body );
// Add this line
var ui = HtmlService.createTemplateFromFile('ModeLessDialog');
ui.body = URL; // Pass url to template
ui = ui.evaluate().setWidth(1000).setHeight(500);
SpreadsheetApp.getUi().showModalDialog(ui, TITLE);
var insertion_position = event.range.getRow() ;
var tss_bis = SpreadsheetApp.openById(SPREADSHEET_ID);
var sheet_bis = tss_bis.getSheets()[0];
var numRows_bis = sheet_bis.getLastRow();
var lastColumn_bis = sheet_bis.getLastColumn();
//from the second line car the first line we have the headers
var data_sheet = sheet_bis.getRange(1,1,numRows_bis,lastColumn_bis).getDisplayValues();
if(body)
{
var ok = 0; //pour l'instant il n'y a pas de tableau trouvé (avec 8 lignes) qui nous interesse pour mettre à jour dans la feuille de calcul
var numChildren=body.getNumChildren();
var compteur=0;
//tant qu'on n'a pas du tableau on va parcourir (car on n'est pas sur d'avoir le 4 comme enfant (Numero_Enfant_Tableau_Template) car l'utilisateur pourra modifier/insérer un prargraphe une image etc.
while(ok ==0 && compteur<numChildren)
{
var child=body.getChild(compteur);
/** ============On est concerné par le premier tableau seulement qui a au plus 8 lignes d'information ================**/
Logger.log('Le type dans la boucle ' + child.getType());
//on a trouvé un tableau qui nous interesse et qui a au plus 8 lignes d'information **/
if(child.getType()==DocumentApp.ElementType.TABLE && child.asTable().getNumRows() >= 8)
{
//on a trouve notre premier tableau la variable ok = 1
ok=1;
/** Le nombre de lignes dans le premier tableau avec au plus 8 lignes qui nous interessent **/
var numrows = child.asTable().getNumRows();
Logger.log('Le nombre de lignes dans notre Google Doc ' + numrows);
/** on va parcourir notre tableau pour récuperer les champs qui nous interessent **/
var k = 1; //on sait que c'est l'information à droite qui nous interessent on va éviter une boucle inutile
var celltxt,trange;
/** On va mettre la valeur du celltxt dans le spreadsheet et on va ajuster automatiquement la colonne avec la méthode autoResizeColumn **/
celltxt=child.asTable().getCell(0, k).editAsText().getText();
Logger.log('La valeur (à droite) dans le tableau ' + celltxt);
trange = sheet_bis.getRange(insertion_position, column_name_project); //l'emplacement correspondant
trange.setValue(celltxt);
celltxt=child.asTable().getCell(1, k).editAsText().getText();
Logger.log('La valeur (à droite) dans le tableau ' + celltxt);
trange = sheet_bis.getRange(insertion_position, column_code_project); //l'emplacement correspondant
trange.setValue(celltxt);
celltxt=child.asTable().getCell(2, k).editAsText().getText();
Logger.log('La valeur (à droite) dans le tableau ' + celltxt);
trange = sheet_bis.getRange(insertion_position, column_chef_project); //l'emplacement correspondant
trange.setValue(celltxt);
celltxt=child.asTable().getCell(3, k).editAsText().getText();
Logger.log('La valeur (à droite) dans le tableau ' + celltxt);
trange = sheet_bis.getRange(insertion_position, column_service); //l'emplacement correspondant
trange.setValue(celltxt);
celltxt=child.asTable().getCell(4, k).editAsText().getText();
Logger.log('La valeur (à droite) dans le tableau ' + celltxt);
trange = sheet_bis.getRange(insertion_position, column_other_services); //l'emplacement correspondant
trange.setValue(celltxt);
celltxt=child.asTable().getCell(5, k).editAsText().getText();
Logger.log('La valeur (à droite) dans le tableau ' + celltxt);
trange = sheet_bis.getRange(insertion_position, column_type_of_project); //l'emplacement correspondant
trange.setValue(celltxt);
celltxt=child.asTable().getCell(6, k).editAsText().getText();
Logger.log('La valeur (à droite) dans le tableau ' + celltxt);
trange = sheet_bis.getRange(insertion_position, column_perimeter); //l'emplacement correspondant
trange.setValue(celltxt);
celltxt=child.asTable().getCell(7, k).editAsText().getText();
Logger.log('La valeur (à droite) dans le tableau ' + celltxt);
trange = sheet_bis.getRange(insertion_position, column_date_project); //l'emplacement correspondant
trange.setValue(celltxt);
}
compteur++; /** on va incrementer le compteur jusqu'à on trouve le tableau qui nous interessent **/
}
}
event.range.setValue("FALSE");
}
catch(err) {
Logger.log(err);
}
}
}
google_doc.saveAndClose();
}
Using while loop, I want to alert names with their number from an array. I also have to put every name in a single alert.
Script:
var voetbalteam = 1;
var spelers = ["Nobert Alblas", "Kostas Lamprou", "André Onana", "Benjamin van Leer", "Léon Bergsma", "Damil Dankerlui", "Matthijs de Ligt", "Mitchell Dijks", "Luis Orejuela", "Daley Sinkgraven", "Joël Veltman", "Nick Viergever", "Max Wöber", "Deyovaisio Zeefuik", "Frenkie de Jong", "Siem de Jong", "Carel Eiting", "Noussair Mazaoui", "Lasse Schöne", "Donny van de Beek", "Klaas Jan Huntelaar", "Kasper Dolberg", "Justin Kluivert"];
while ((voetbalteam <= 23) + (spelers >= 0)){
alert("Ik ben " + spelers[spelers] + " En ik ben de " + voetbalteam + "e speler.");
spelers ++;
voetbalteam ++;
}
Use forEach() to loop over the array.
var voetbalteam = 1;
var spelers = ["Nobert Alblas", "Kostas Lamprou", "André Onana", "Benjamin van Leer", "Léon Bergsma", "Damil Dankerlui", "Matthijs de Ligt", "Mitchell Dijks", "Luis Orejuela", "Daley Sinkgraven", "Joël Veltman", "Nick Viergever", "Max Wöber", "Deyovaisio Zeefuik", "Frenkie de Jong", "Siem de Jong", "Carel Eiting", "Noussair Mazaoui", "Lasse Schöne", "Donny van de Beek", "Klaas Jan Huntelaar", "Kasper Dolberg", "Justin Kluivert"];
spelers.forEach(function(key, value){
console.log("Ik ben " + key + " En ik ben de " + (value + 1) + "e speler.");
});
Using a while loop, use voetbalteam as an iterator and increment it inside the while loop.
var voetbalteam = 0;
var spelers = ["Nobert Alblas", "Kostas Lamprou", "André Onana", "Benjamin van Leer", "Léon Bergsma", "Damil Dankerlui", "Matthijs de Ligt", "Mitchell Dijks", "Luis Orejuela", "Daley Sinkgraven", "Joël Veltman", "Nick Viergever", "Max Wöber", "Deyovaisio Zeefuik", "Frenkie de Jong", "Siem de Jong", "Carel Eiting", "Noussair Mazaoui", "Lasse Schöne", "Donny van de Beek", "Klaas Jan Huntelaar", "Kasper Dolberg", "Justin Kluivert"];
while (voetbalteam < spelers.length){
console.log("Ik ben " + spelers[voetbalteam] + " En ik ben de " + (voetbalteam + 1) + "e speler.");
voetbalteam ++;
}
consider using console.log() instead of alert() when you are coding.
alert() is blocking
alert() cannot be easily suppressed in non-debug environment
console typically formats your objects nicely and allows to traverse
them
logging statements often have an interactive pointer to code which
issued logging statement
you cannot look at more than one alert() message at a time
consoles can have different logging levels with intuitive formatting
The above text was taken from here
If you really want to use a while loop, try this:
var voetbalteam = 0;
var spelers = ["Nobert Alblas", "Kostas Lamprou", "André Onana", "Benjamin van Leer", "Léon Bergsma", "Damil Dankerlui", "Matthijs de Ligt", "Mitchell Dijks", "Luis Orejuela", "Daley Sinkgraven", "Joël Veltman", "Nick Viergever", "Max Wöber", "Deyovaisio Zeefuik", "Frenkie de Jong", "Siem de Jong", "Carel Eiting", "Noussair Mazaoui", "Lasse Schöne", "Donny van de Beek", "Klaas Jan Huntelaar", "Kasper Dolberg", "Justin Kluivert"];
while (voetbalteam < spelers.length){
alert("Ik ben " + spelers[voetbalteam] + " En ik ben de " + (voetbalteam + 1) + "e speler.");
voetbalteam++;
}
I have documents in which i need to highlight that a person was quoted. So I'm looking for all text that's enclosed by quotes...I'm using the below code, which works but it only captures the first occurence..
var str = 'L\'armée sud-coréenne accuse la Corée du Nord d\'avoir lancé \"plusieurs\" missiles \"balistiques interdits qui ont franchi une distance\" d\'environ 1000 kilomètres avant de tomber au \"large de la côte est du pays communiste.\" '
var reg = new RegExp(/"(.*?)"/);
var matches = str.match(reg);
for (var i = 0; i < matches.length; i++) {
var s = matches[i];
str = str.replace(matches[i], '<span style="color:blue">' + matches[i] + '</span>');
matches[i] = s;
}
Make your Regex global:
The g modifier is used to perform a global match (find all matches rather than stopping after the first match).
var str = 'L\'armée sud-coréenne accuse la Corée du Nord d\'avoir lancé \"plusieurs\" missiles \"balistiques interdits qui ont franchi une distance\" d\'environ 1000 kilomètres avant de tomber au \"large de la côte est du pays communiste.\" '
var reg = new RegExp(/"(.*?)"/g); //notice /g, making the expression global
var matches = str.match(reg);
for (var i = 0; i < matches.length; i++) {
var s = matches[i];
str = str.replace(matches[i], '<span style="color:blue">' + matches[i] + '</span>');
matches[i] = s;
}
document.getElementById("myDiv").innerHTML = str;
Making your expression global guarantees all instances of the quotes match.
JSFiddle: https://jsfiddle.net/zjxjub96/
To illustrate what #Casimir says in his comment, here is a little example:
var str = 'L\'armée sud-coréenne accuse la Corée du Nord d\'avoir lancé \"plusieurs\" missiles \"balistiques interdits qui ont franchi une distance\" d\'environ 1000 kilomètres avant de tomber au \"large de la côte est du pays communiste.\" '
str = str.replace(/"(.*?)"/g, '<span style="color:blue">$&</span>')
document.getElementById("myDiv").innerHTML = str;
<div id="myDiv">
</div>
Notice that this way is easier, and doesn't require a for loop.
JSFiddle: https://jsfiddle.net/zjxjub96/1/
I have a problem with keeping sliders in sync.
Sliders preview
If I +1 on one of the four sliders, then the others must be substracted with 1/3.
What is the best way to perform this action?
I tried through Javascript already but can't come up with a working code. The selected slider does change value, but the 3 others give weird numbers.
The oninput() method is called when changing one of the sliders. When selecting a sliders and pressing the arrows keys to change the value then nothing happens. When drag and dropping a new value on the slider, also nothing happens. Only when sliding very rapidly.
When clicking on a new value on the slider, it does work somehow..
What am I doing wrong here?
this is the whole function, some variables are written in Dutch...
Code preview:
function showValueSub(sliderValue, parent, aantalKinderen, totaalbedragCategorie, echteParentId, teller, aantalSiblings, opgeroepenDoorHoofdCategorie) {
/*
het labeltje onder de afbeelding van de hoofdcategorie moet niet meer worden aangepast.
document.getElementById("subcat" + range).innerHTML = newValue + " Euro";
##
Parameters:
parent=het begrotingsId van het huidig element.
echteParentId= het begrotingsId van de parent
##
*/
//alert('test');
//###################################################################################################################################################
//#LOOPEN OVER DE SIBLINGS
//enkel loopen over siblings als deze functie wordt uitgevoerd door huidig element, en niet de parent.
//eerst het outputelement onder de slider aanpassen
var siblingElement = document.getElementById(echteParentId + "input" + teller);
if (siblingElement != null) var siblingSlider = parseInt(siblingElement.getAttribute("onchangeviaparent"));
if (siblingElement != null && siblingSlider != 1) {
//als het niet is opgeroepen door een hoofdcategorie: dan output en input aanpasen van huidig element
var huidigOutputElement = document.getElementById(echteParentId + "output" + teller);
huidigOutputElement.innerText = sliderValue;
var aantalAanpasbareSiblings = 0;
var teVerdelenBedragSiblings = 0;
for (var i = 0; i < aantalSiblings - 1; i++) {
var siblingElement = document.getElementById(echteParentId + "." + i);
//tellen hoeveel kindelementen er zijn die aanpasbaar zijn.
if (siblingElement.getAttribute("categoriestatus") != "NIET_AANPASBAAR")
aantalAanpasbareSiblings++;
}
if (aantalAanpasbareSiblings == 0) aantalAanpasbareSiblings = 1;
if (vorigeSliderValueSibling != null)
teVerdelenBedragSiblings = (sliderValue - vorigeSliderValueSibling) / aantalAanpasbareSiblings; //te verdelen bedrag per aanpasbaar siblingElement
else
teVerdelenBedragSiblings = Math.round(sliderValue / aantalAanpasbareSiblings).toFixed(2); //te verdelen bedrag per aanpasbaar siblingElement
for (var i = 0; i < aantalSiblings; i++) {
//het huidig subelement mag niet aangepast worden, checken met een if.
var siblingElement = document.getElementById(echteParentId + "." + i);
if (siblingElement != document.getElementById(echteParentId + "." + teller)) {
if (siblingElement.getAttribute("categoriestatus") != "NIET_AANPASBAAR") {
//in het p element staat een bedrag + de string "EURO".
//eigen p element ophalen
var siblingElementMetBedrag = document.getElementById(echteParentId + "." + i + "p");
var bedrag = parseFloat(siblingElementMetBedrag.innerHTML.substring(0, siblingElementMetBedrag.innerHTML.length - 5).trim());
bedrag -= teVerdelenBedragSiblings; //aftrekken ipv optellen
siblingElementMetBedrag.innerHTML = Math.round(bedrag).toFixed(2) + " Euro";
//siblinginput(slider) element ophalen en proberen aan te passen
var siblingSliderElement = document.getElementById(echteParentId + "input" + i);
if (siblingSliderElement != null) siblingSliderElement.value = Math.round(siblingSliderElement.value - teVerdelenBedragSiblings).toFixed(2);
//output van sibling aanpassen
var siblingSliderOutput =document.getElementById(echteParentId + "output" + i);
if (siblingSliderOutput != null)
siblingSliderOutput.value = Math.round(siblingSliderOutput.value - teVerdelenBedragSiblings).toFixed(2);
}
}
}
}
vorigeSliderValueSibling = sliderValue;
//###################################################################################################################################################
//#LOPEN OVER DE KINDEREN.
var aantalAanpasbareKinderen = 0;
for (var i = 0; i < aantalKinderen; i++) {
var kindElement = document.getElementById(parent + "." + i);
//tellen hoeveel kindelementen er zijn die aanpasbaar zijn.
if (kindElement.getAttribute("categoriestatus") != "NIET_AANPASBAAR")
aantalAanpasbareKinderen++;
}
//als er geen aanpasbarekinderen gevonden zijn, deze standaard op 1 zetten want
//delen door 0 gaat niet.
if (aantalAanpasbareKinderen == 0) aantalAanpasbareKinderen = 1;
//checken of de slider al een keer is aangepast, zo ja huidig bedrag van de slider verminderen met vorige waarde van de slider
if (vorigeSliderValueSub != null)
teVerdelenBedrag = (sliderValue - vorigeSliderValueSub) / aantalAanpasbareKinderen; //te verdelen bedrag per aanpasbaar kindElement
else
teVerdelenBedrag = Math.round(sliderValue / aantalAanpasbareKinderen).toFixed(2); //te verdelen bedrag per aanpasbaar kindElement
for (var i = 0; i < aantalKinderen; i++) {
var kindElement = document.getElementById(parent + "." + i);
if (kindElement.getAttribute("categoriestatus") != "NIET_AANPASBAAR") {
//in het p element staat een bedrag + de string "EURO".
//eigen p element ophalen
var kindElementMetBedrag = document.getElementById(parent + "." + i + "p");
var bedrag = parseFloat(kindElementMetBedrag.innerHTML.substring(0, kindElementMetBedrag.innerHTML.length - 5).trim());
bedrag += teVerdelenBedrag;
kindElementMetBedrag.innerHTML = bedrag + " Euro";
//kindinput element ophalen en proberen aan te passen
var kindSliderElement = document.getElementById(parent + "input" + i);
if (kindSliderElement != null) kindSliderElement.value = sliderValue / aantalAanpasbareKinderen;
}
}
//###################################################################################################################################################
vorigeSliderValueSub = sliderValue;
//alert(siblingSlider.innerHTML);
if (siblingSlider != null) {
$("#" + echteParentId + "input" + teller).attr('onchangeviaparent', '0');
//siblingSlider.onchangeviaparent = '0';
//alert(parseInt(siblingSlider.getAttribute("onchangeviaparent")));
}
//document.getElementById(echteParentId + "." + teller).setAttribute("onchangeViaParent", "0");
//alert(document.getElementById(echteParentId + "input" + teller).getAttribute("onchangeViaParent"));
}
Good afternoon, I am developing a small script that analyzes the DOM of an HTML page and write on screen the tree of nodes.
It is a simple function that is called recursively for get all nodes and their children. The information for each node is stored in an array (custom object).
I have gotten get all the nodes in the DOM, but not how to paint in a tree through nested lists.
JSFIDLE
https://jsfiddle.net/06krpdyh/
HTML
<html>
<head>
<title>Formulario para validar</title>
<script type="text/javascript" src="actividad_1.js">Texto script</script>
</head>
<body>
<p>Primer texto que se visualiza en la Pagina</p>
<div>Esto es un div</div>
<div>Otro div que me encuentro</div>
<p>Hay muchos parrafos</p>
<ul>
<li>Lista 1</li>
<li>Lista 2</li>
<li>Lista 3</li>
</ul>
<button type="button" id="muestra_abol">Muestra Arbol DOM</button>
</body>
</html>
JS
// Ejecuta el script una vez se ha cargado toda la página, para evitar que el BODY sea NULL.
window.onload = function(){
// Evento de teclado al hacer click sobre el boton que muestra el arbol.
document.getElementById("muestra_abol").addEventListener("click", function(){
muestraArbol();
});
// Declara el array que contendrá los objetos con la información de los nodos.
var nodeTree = [];
// Recoge el nodo raíz del DOM.
var obj_html = document.documentElement;
// Llama a la función que genera el árbol de nodos de la página.
getNodeTree(obj_html);
console.log(nodeTree);
// Función que recorre la página descubriendo todo el árbol de nodos.
function getNodeTree(node)
{
// Comprueba si el nodo tiene hijos.
if (node.hasChildNodes())
{
// Recupera la información del nodo.
var treeSize = nodeInfo(node);
// Calcula el índice del nodo actual.
var treeIndex = treeSize - 1;
// Recorre los hijos del nodo.
for (var j = 0; j < node.childNodes.length; j++)
{
// Comprueba, de forma recursiva, los hijos del nodo.
getNodeTree(node.childNodes[j]);
}
}
else
{
return false;
}
}
// Función que devuelve la información de un nodo.
function nodeInfo(node,)
{
// Declara la variable que contendrá la información.
var data = {
node: node.nodeName,
parent: node.parentNode.nodeName,
childs: [],
content: (typeof node.text === 'undefined'? "" : node.text)
}
var i = nodeTree.push(data);
return i;
}
// Función que devuelve los datos de los elementos hijos de un nodo.
function muestraArbol()
{
var txt = "";
// Comprueba si existen nodos.
if (nodeTree.length > 0)
{
// Recorre los nodos.
for (var i = 0; i < nodeTree.length; i++)
{
txt += "<ul><li>Nodo: " + nodeTree[i].node + "</li>";
txt += "<li> Padre: " + nodeTree[i].parent + "</li>";
txt += "<li>Contenido: " + nodeTree[i].content + "</li>";
txt += "</ul>";
}
document.write(txt);
}
else
{
document.write("<h1>No existen nodos en el DOM.</h1>");
}
}
};
Does anyone comes up how to draw a nested tree to glance at the parent and child nodes you distinguish?
Greetings and thank you
You have a recursive DOM reader, but you also need a recursive outputter. You're also dealing with a one dimensional array when you need a multi-level object (tree).
We'll start with refactoring getNodeTree. Instead of adding to a global array (nodeTree in your code), let's have it return a tree:
function getNodeTree (node) {
if (node.hasChildNodes()) {
var children = [];
for (var j = 0; j < node.childNodes.length; j++) {
children.push(getNodeTree(node.childNodes[j]));
}
return {
nodeName: node.nodeName,
parentName: node.parentNode.nodeName,
children: children,
content: node.innerText || "",
};
}
return false;
}
Same for muestraArbol (for our monolingual friends out there, it means "show tree"): We'll have it work recursively and return a string containing nested lists:
function muestraArbol (node) {
if (!node) return "";
var txt = "";
if (node.children.length > 0) {
txt += "<ul><li>Nodo: " + node.nodeName + "</li>";
txt += "<li> Padre: " + node.parentName + "</li>";
txt += "<li>Contenido: " + node.content + "</li>";
for (var i = 0; i < node.children.length; i++)
if (node.children[i])
txt += "<li> Hijos: " + muestraArbol(node.children[i]) + "</li>";
txt += "</ul>";
}
return txt;
}
Finally, if we put it together in a snippet:
var nodeTree = getNodeTree(document.documentElement);
console.log(nodeTree);
function getNodeTree(node) {
if (node.hasChildNodes()) {
var children = [];
for (var j = 0; j < node.childNodes.length; j++) {
children.push(getNodeTree(node.childNodes[j]));
}
return {
nodeName: node.nodeName,
parentName: node.parentNode.nodeName,
children: children,
content: node.innerText || "",
};
}
return false;
}
function muestraArbol(node) {
if (!node) return "";
var txt = "";
if (node.children.length > 0) {
txt += "<ul><li>Nodo: " + node.nodeName + "</li>";
txt += "<li> Padre: " + node.parentName + "</li>";
txt += "<li>Contenido: " + node.content + "</li>";
for (var i = 0; i < node.children.length; i++)
if (node.children[i])
txt += "<li> Hijos: " + muestraArbol(node.children[i]) + "</li>";
txt += "</ul>";
}
return txt;
}
document.getElementById("muestra_abol").addEventListener("click", function() {
document.getElementById("result").innerHTML = muestraArbol(nodeTree);
});
<title>Formulario para validar</title>
<body>
<p>Primer texto que se visualiza en la Pagina</p>
<div>Esto es un div</div>
<div>Otro div que me encuentro</div>
<p>Hay muchos parrafos</p>
<ul>
<li>Lista 1</li>
<li>Lista 2</li>
<li>Lista 3</li>
</ul>
<button type="button" id="muestra_abol">Muestra Arbol DOM</button>
<div id="result"></div>
</body>
Finally: My apologies, for my Spanish-JavaScript reading skills are not in their prime. :)