So I have a checkers game, and I am trying to get it so that you can jump over multiple spaces. It works if you jump the max amount of spaces, but if you don't, say you can jump over two spaces, and you choose to jump over only one, it still removes both pieces even though you only jumped over one of the pieces. I think the problem has is inside the checkForJump() function, and it seems like every time the function is called, it returns the same array, any help would be appreciated.
function checkForJump(buttonSelected, remove, isRoot) {
if(isRoot)
{
clearAvailableMoves();
switchPiece();
}
let adjacentValue = 0;
let jumpNotValid = false;
let RemoveTiles = remove;
for (let i = 0; i < adjacentTileValues.length; i++) {
adjacentValue = adjacentTileValues[i];
if (board.value[adjacentValue + buttonSelected] == enemyPiece && board.value[buttonSelected + (adjacentValue * 2)] == empty) {
if (isSpaceAlreadyInArray(buttonSelected + adjacentValue * 2, i) == false) {
RemoveTiles.push(buttonSelected + adjacentValue);
let tile = new jumpTile(buttonSelected + (adjacentValue * 2));
RemoveTiles.push(buttonSelected + adjacentValue);
console.log("removeTiles" + RemoveTiles);
for (let k = 0; k < RemoveTiles.length; k++) {
tile.tilesToRemove.push(RemoveTiles[k]);
}
console.log("tile.tilesToRemove: " + tile.tilesToRemove);
availableSpaces[i].push(tile);
checkForJump(buttonSelected + (adjacentValue * 2), RemoveTiles,false);
console.log("available spaces = " + availableSpaces);
}
}
}
};
Here is some of the other code, relating to that could also be the source of the problem
function jumpTile(tileID) {
this.tilesToRemove = [];
this.tileID = tileID;
};
let numBlackPieces = 12;
let numWhitePieces = 12;
let adjacentTileValues = [7, 9, -7, -9];
let availableSpaces = [
[],
[],
[],
[]
];
function checkValidSpace(buttonPressed, piece) {
// if button is adjacent to selectedbutton
if (buttonPressed == selectedButton + 7 || buttonPressed == selectedButton + 9 || buttonPressed == selectedButton - 9 || buttonPressed == selectedButton - 7) {
return true;
} else {
let valid = false;
// checks if there is a valid jump
checkForJump(selectedButton,[],true);
// foreach of the possible tiles, if the button pressed is one of them than remove all pieces in that tiles remove list
for (let i = 0; i < availableSpaces.length; i++) {
for (let j = 0; j < availableSpaces[i].length; j++) {
if (buttonPressed == availableSpaces[i][j].tileID) {
valid = true;
console.log("availableSpaces[" + i + j + "] is " + availableSpaces[i][j].tileID + "");
remove(availableSpaces[i][j].tilesToRemove);
return true;
}
}
}
if (valid == false)
return false;
}
}
function checkForJump(buttonSelected, remove, isRoot) {
if(isRoot)
{
clearAvailableMoves();
switchPiece();
}
let adjacentValue = 0;
let jumpNotValid = false;
let RemoveTiles = remove;
for (let i = 0; i < adjacentTileValues.length; i++) {
adjacentValue = adjacentTileValues[i];
if (board.value[adjacentValue + buttonSelected] == enemyPiece && board.value[buttonSelected + (adjacentValue * 2)] == empty) {
if (isSpaceAlreadyInArray(buttonSelected + adjacentValue * 2, i) == false) {
RemoveTiles.push(buttonSelected + adjacentValue);
let tile = new jumpTile(buttonSelected + (adjacentValue * 2));
RemoveTiles.push(buttonSelected + adjacentValue);
console.log("removeTiles" + RemoveTiles);
for (let k = 0; k < RemoveTiles.length; k++) {
tile.tilesToRemove.push(RemoveTiles[k]);
}
console.log("tile.tilesToRemove: " + tile.tilesToRemove);
availableSpaces[i].push(tile);
checkForJump(buttonSelected + (adjacentValue * 2), RemoveTiles,false);
console.log("available spaces = " + availableSpaces);
}
}
}
};
function isSpaceAlreadyInArray(spot, arrayIndex) {
let SpaceAlreadyInArray = false;
for (let j = 0; j < availableSpaces[arrayIndex].length; j++) {
if (availableSpaces[arrayIndex][j].tileID == spot) {
SpaceAlreadyInArray = true;
}
}
return SpaceAlreadyInArray;
}
function clearAvailableMoves() {
for (let i = 0; i < availableSpaces.length; i++) {
availableSpaces[i].pop();
}
}
function remove(removeList, button) {
for (let i = 0; i < removeList.length; i++) {
board.value[removeList[i]] = empty;
board.buttons[removeList[i]].textContent = empty;
if (piece == black) {
numBlackPieces--;
checkForWin(numBlackPieces);
} else if (piece == white) {
numWhitePieces--;
checkForWin(numWhitePieces);
}
}
clearAvailableMoves();
};
I was able to get some help from a previous post where I wanted to highlight words dynamically as a user entered text.
The previous condition would highlight a word if it began with "t", now I want to update this condition to highlight any words that meet a condition based on dictionary values (I call JavaScript's built in object a dictionary).
For example, if I have a dictionary dict = {"test": 5.0, "check": 4.0, "stop": -1.5, "fair": 2.0} how would I have the script highlight words whose value was greater than 2.0?
Failed code:
dict = {"test": 5.0, "check": 4.0, "stop": -1.5, "fair": 2.0}
function highlighter(ev) {
// Get current cursor position
const currpos = getSelectionDirection(ev) !== 'forward' ? getSelectionStart(ev) : getSelectionEnd(ev);
// Change innerHTML to innerText, you
// dont need to parse HTML code here
var content = ev.innerText;
var tokens = content.split(" ");
for (var i = 0; i < tokens.length; i++) {
if (dict[tokens[i][0]] > 2.0) {
tokens[i] = "<mark style='background-color:red; color:white;'>" + tokens[i] + "</mark>";
}
}
ev.innerHTML = tokens.join(" ");
// Set cursor on its proper position
setSelectionRange(ev, currpos, currpos);
}
/* NOT REQUIRED AT ALL, JUST TO MAKE INTERACTION MORE PLEASANT */
.container {
outline: none;
border: 3px solid black;
height: 100px;
width: 400px;
}
<div class="container" onkeypress=highlighter(this) contenteditable>
</div>
<script>
// Usage:
// var x = document.querySelector('[contenteditable]');
// var caretPosition = getSelectionDirection(x) !== 'forward' ? getSelectionStart(x) : getSelectionEnd(x);
// setSelectionRange(x, caretPosition + 1, caretPosition + 1);
// var value = getValue(x);
// it will not work with "<img /><img />" and, perhaps, in many other cases.
function isAfter(container, offset, node) {
var c = node;
while (c.parentNode != container) {
c = c.parentNode;
}
var i = offset;
while (c != null && i > 0) {
c = c.previousSibling;
i -= 1;
}
return i > 0;
}
function compareCaretPositons(node1, offset1, node2, offset2) {
if (node1 === node2) {
return offset1 - offset2;
}
var c = node1.compareDocumentPosition(node2);
if ((c & Node.DOCUMENT_POSITION_CONTAINED_BY) !== 0) {
return isAfter(node1, offset1, node2) ? +1 : -1;
} else if ((c & Node.DOCUMENT_POSITION_CONTAINS) !== 0) {
return isAfter(node2, offset2, node1) ? -1 : +1;
} else if ((c & Node.DOCUMENT_POSITION_FOLLOWING) !== 0) {
return -1;
} else if ((c & Node.DOCUMENT_POSITION_PRECEDING) !== 0) {
return +1;
}
}
function stringifyElementStart(node, isLineStart) {
if (node.tagName.toLowerCase() === 'br') {
if (true) {
return '\n';
}
}
if (node.tagName.toLowerCase() === 'div') { // Is a block-level element?
if (!isLineStart) { //TODO: Is not at start of a line?
return '\n';
}
}
return '';
}
function* positions(node, isLineStart = true) {
console.assert(node.nodeType === Node.ELEMENT_NODE);
var child = node.firstChild;
var offset = 0;
yield {node: node, offset: offset, text: stringifyElementStart(node, isLineStart)};
while (child != null) {
if (child.nodeType === Node.TEXT_NODE) {
yield {node: child, offset: 0/0, text: child.data};
isLineStart = false;
} else {
isLineStart = yield* positions(child, isLineStart);
}
child = child.nextSibling;
offset += 1;
yield {node: node, offset: offset, text: ''};
}
return isLineStart;
}
function getCaretPosition(contenteditable, textPosition) {
var textOffset = 0;
var lastNode = null;
var lastOffset = 0;
for (var p of positions(contenteditable)) {
if (p.text.length > textPosition - textOffset) {
return {node: p.node, offset: p.node.nodeType === Node.TEXT_NODE ? textPosition - textOffset : p.offset};
}
textOffset += p.text.length;
lastNode = p.node;
lastOffset = p.node.nodeType === Node.TEXT_NODE ? p.text.length : p.offset;
}
return {node: lastNode, offset: lastOffset};
}
function getTextOffset(contenteditable, selectionNode, selectionOffset) {
var textOffset = 0;
for (var p of positions(contenteditable)) {
if (selectionNode.nodeType !== Node.TEXT_NODE && selectionNode === p.node && selectionOffset === p.offset) {
return textOffset;
}
if (selectionNode.nodeType === Node.TEXT_NODE && selectionNode === p.node) {
return textOffset + selectionOffset;
}
textOffset += p.text.length;
}
return compareCaretPositons(selectionNode, selectionOffset, contenteditable, 0) < 0 ? 0 : textOffset;
}
function getValue(contenteditable) {
var value = '';
for (var p of positions(contenteditable)) {
value += p.text;
}
return value;
}
function setSelectionRange(contenteditable, start, end) {
var selection = window.getSelection();
var s = getCaretPosition(contenteditable, start);
var e = getCaretPosition(contenteditable, end);
selection.setBaseAndExtent(s.node, s.offset, e.node, e.offset);
}
//TODO: Ctrl+A - rangeCount is 2
function getSelectionDirection(contenteditable) {
var selection = window.getSelection();
var c = compareCaretPositons(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
return c < 0 ? 'forward' : 'none';
}
function getSelectionStart(contenteditable) {
var selection = window.getSelection();
var c = compareCaretPositons(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
return c < 0 ? getTextOffset(contenteditable, selection.anchorNode, selection.anchorOffset) : getTextOffset(contenteditable, selection.focusNode, selection.focusOffset);
}
function getSelectionEnd(contenteditable) {
var selection = window.getSelection();
var c = compareCaretPositons(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
return c < 0 ? getTextOffset(contenteditable, selection.focusNode, selection.focusOffset) : getTextOffset(contenteditable, selection.anchorNode, selection.anchorOffset);
}
</script>
Check below code I used this Cool js lib jQuery highlightTextarea and as per your requirements, I loop through your dict object and push only those words that have a value greater than 2.0.
dict = {"test": 5.0, "check": 4.0, "stop": -1.5, "fair": 2.0}
var words = [];
Object.keys(dict).forEach(function(key) {
if( dict[key] > 2 ){
words.push(key);
}
});
$('textarea').highlightTextarea({
words: words,
caseSensitive: false
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://garysieling.github.io/jquery-highlighttextarea/dist/jquery-ui/themes/smoothness/jquery-ui.min.css">
<link rel="stylesheet" href="http://garysieling.github.io/jquery-highlighttextarea/dist/jquery-highlighttextarea/jquery.highlighttextarea.min.css">
<script src="http://garysieling.github.io/jquery-highlighttextarea/dist/jquery-ui/ui/minified/jquery-ui.min.js"></script>
<script src="http://garysieling.github.io/jquery-highlighttextarea/dist/jquery-highlighttextarea/jquery.highlighttextarea.min.js"></script>
<textarea id="demo-case" cols="50" rows="3" style="background: none;" spellcheck="true">This is a test you can check or stop it will be fair enough.</textarea>
More options here http://garysieling.github.io/jquery-highlighttextarea/#options
Other example here http://garysieling.github.io/jquery-highlighttextarea/examples.html
I have create a table with pagination is every thing is fine and good but only one issue i have face and not finding any good solution can u please any body solve this and let us know where is the error int this code .
Issue is
if i click to s.no then shorting is not fine.
i used to this function for shorting _tableCustomFun.sortTable
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
my code is below .
myTableObjData = {
'head':['s.no', 'name', 'per%', 'price'],
'body': [
[1,'rohit', '9%', 23],
[10,'rohit azad', '19%', 230],
[8,'rohit', '39%', 111],
]
}
var _tableCustomFun = {
create_sample_table: function(parentNode, head, body, foot, data) {
if (typeof head == "undefined") {head = true;}
if (typeof body == "undefined") {body = true;}
if (typeof foot == "undefined") {foot = true;}
data = myTableObjData;
var table = document.createElement("table");
var tr, th, td;
// header
tr = document.createElement("tr");
var headers = data.head || [];
for (var i=0;i<headers.length;i++) {
th = document.createElement("th");
span = document.createElement("span");
span.innerHTML = headers[i];
th.appendChild(span);
tr.appendChild(th);
}
if (head) {
var thead = document.createElement("thead");
thead.appendChild(tr);
table.appendChild(thead);
} else {
table.appendChild(tr);
}
// end header
// body
var table_body = data.body || [];
if (body) {
var tbody = document.createElement("tbody");
}
for (var i=0;i<table_body.length;i++) {
tr = document.createElement("tr");
for (var j=0;j<table_body[i].length;j++) {
td = document.createElement("td");
td.innerHTML = table_body[i][j];
tr.appendChild(td);
}
if (body) {
tbody.appendChild(tr);
} else {
table.appendChild(tr);
}
}
if (body) {
table.appendChild(tbody);
}
// end body
if (parentNode) {
parentNode.innerHTML = "";
parentNode.appendChild(table);
}
//return table;
},
paginator: function(config) {
// throw errors if insufficient parameters were given
if (typeof config != "object")
throw "Paginator was expecting a config object!";
if (typeof config.get_rows != "function" && !(config.table instanceof Element))
throw "Paginator was expecting a table or get_row function!";
// get/set if things are disabled
if (typeof config.disable == "undefined") {
config.disable = false;
}
// get/make an element for storing the page numbers in
var box;
if (!(config.box instanceof Element)) {
config.box = document.createElement("div");
}
box = config.box;
// get/make function for getting table's rows
if (typeof config.get_rows != "function") {
config.get_rows = function () {
var table = config.table
var tbody = table.getElementsByTagName("tbody")[0]||table;
// get all the possible rows for paging
// exclude any rows that are just headers or empty
children = tbody.children;
var trs = [];
for (var i=0;i<children.length;i++) {
if (children[i].nodeType = "tr") {
if (children[i].getElementsByTagName("td").length > 0) {
trs.push(children[i]);
}
}
}
return trs;
}
}
var get_rows = config.get_rows;
var trs = get_rows();
// get/set rows per page
if (typeof config.rows_per_page == "undefined") {
var selects = box.getElementsByTagName("select");
if (typeof selects != "undefined" && (selects.length > 0 && typeof selects[0].selectedIndex != "undefined")) {
config.rows_per_page = selects[0].options[selects[0].selectedIndex].value;
} else {
config.rows_per_page = 150;
}
}
var rows_per_page = config.rows_per_page;
// get/set current page
if (typeof config.page == "undefined") {
config.page = 1;
}
var page = config.page;
// get page count
var pages = (rows_per_page > 0)? Math.ceil(trs.length / rows_per_page):1;
// check that page and page count are sensible values
if (pages < 1) {
pages = 1;
}
if (page > pages) {
page = pages;
}
if (page < 1) {
page = 1;
}
config.page = page;
// hide rows not on current page and show the rows that are
for (var i=0;i<trs.length;i++) {
if (typeof trs[i]["data-display"] == "undefined") {
trs[i]["data-display"] = trs[i].style.display||"";
}
if (rows_per_page > 0) {
if (i < page*rows_per_page && i >= (page-1)*rows_per_page) {
trs[i].style.display = trs[i]["data-display"];
} else {
// Only hide if pagination is not disabled
if (!config.disable) {
trs[i].style.display = "none";
} else {
trs[i].style.display = trs[i]["data-display"];
}
}
} else {
trs[i].style.display = trs[i]["data-display"];
}
}
// page button maker functions
config.active_class = config.active_class||"active";
if (typeof config.box_mode != "function" && config.box_mode != "list" && config.box_mode != "buttons") {
config.box_mode = "button";
}
if (typeof config.box_mode == "function") {
config.box_mode(config);
} else {
var make_button;
if (config.box_mode == "list") {
make_button = function (symbol, index, config, disabled, active) {
var li = document.createElement("li");
var a = document.createElement("a");
a.href = "#";
a.innerHTML = symbol;
a.addEventListener("click", function (event) {
event.preventDefault();
this.parentNode.click();
return false;
}, false);
li.appendChild(a);
var classes = [];
if (disabled) {
classes.push("disabled");
}
if (active) {
classes.push(config.active_class);
}
li.className = classes.join(" ");
li.addEventListener("click", function () {
if (this.className.split(" ").indexOf("disabled") == -1) {
config.page = index;
_tableCustomFun.paginator(config);
}
}, false);
return li;
}
} else {
make_button = function (symbol, index, config, disabled, active) {
var button = document.createElement("button");
button.innerHTML = symbol;
button.addEventListener("click", function (event) {
event.preventDefault();
if (this.disabled != true) {
config.page = index;
_tableCustomFun.paginator(config);
}
return false;
}, false);
if (disabled) {
button.disabled = true;
}
if (active) {
button.className = config.active_class;
}
return button;
}
}
// make page button collection
var page_box = document.createElement(config.box_mode == "list"?"ul":"div");
if (config.box_mode == "list") {
page_box.className = "pagination";
}
var left = make_button("«", (page>1?page-1:1), config, (page == 1), false);
page_box.appendChild(left);
for (var i=1;i<=pages;i++) {
var li = make_button(i, i, config, false, (page == i));
page_box.appendChild(li);
}
var right = make_button("»", (pages>page?page+1:page), config, (page == pages), false);
page_box.appendChild(right);
if (box.childNodes.length) {
while (box.childNodes.length > 1) {
box.removeChild(box.childNodes[0]);
}
box.replaceChild(page_box, box.childNodes[0]);
} else {
box.appendChild(page_box);
}
}
// make rows per page selector
if (!(typeof config.page_options == "boolean" && !config.page_options)) {
if (typeof config.page_options == "undefined") {
config.page_options = [
{ value: 10, text: '10' },
{ value: 20, text: '20' },
{ value: 50, text: '50' },
{ value: 100,text: '100' },
{ value: 0, text: 'All' }
];
}
var options = config.page_options;
var select = document.createElement("select");
for (var i=0;i<options.length;i++) {
var o = document.createElement("option");
o.value = options[i].value;
o.text = options[i].text;
select.appendChild(o);
}
select.value = rows_per_page;
select.addEventListener("change", function () {
config.rows_per_page = this.value;
_tableCustomFun.paginator(config);
}, false);
box.appendChild(select);
}
// status message
var stat = document.createElement("span");
stat.innerHTML = "On page " + page + " of " + pages
+ ", showing rows " + (((page-1)*rows_per_page)+1)
+ " to " + (trs.length<page*rows_per_page||rows_per_page==0?trs.length:page*rows_per_page)
+ " of " + trs.length;
box.appendChild(stat);
// hide pagination if disabled
if (config.disable) {
if (typeof box["data-display"] == "undefined") {
box["data-display"] = box.style.display||"";
}
box.style.display = "none";
} else {
if (box.style.display == "none") {
box.style.display = box["data-display"]||"";
}
}
// run tail function
if (typeof config.tail_call == "function") {
config.tail_call(config);
}
return box;
},
sortTable: function(table, col, reverse) {
_tableCustomFun.addShortingClass(table, col, reverse);
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
},
makeSortable: function(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {_tableCustomFun.sortTable(table, i, (dir = 1 - dir))});
}(i));
},
makeAllSortable: function(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) _tableCustomFun.makeSortable(t[i]);
},
addShortingClass: function(table, col, reverse){
var thPosition = table.tHead.rows[0].cells[col];
console.log(reverse);
console.log(thPosition);
var _thead = table.tHead.rows[0]
for (var i = 0; i < _thead.cells.length; i++) {
_thead.cells[i].removeAttribute("class");
}
thPosition.classList.add("shorting");
if(reverse == 1){
thPosition.classList.add("up");
}else{
thPosition.classList.add("down");
}
},
init: function(){
var tableNode = document.getElementById("table_box_native");
if(tableNode){
_tableCustomFun.addCssFile();
_tableCustomFun.create_sample_table(document.getElementById("table_box_native"));
_tableCustomFun.paginator({
table: document.getElementById("table_box_native").getElementsByTagName("table")[0],
box: document.getElementById("index_native"),
active_class: "color_page"
});
_tableCustomFun.makeAllSortable();
}
},
addCssFile: function(){
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'css_tablecustom.cms?v=7&minify=1';
link.media = 'all';
head.appendChild(link);
}
}
}
// window.onload = function () {
// _tableCustomFun.init();
// };
document.addEventListener('DOMContentLoaded', function(){_tableCustomFun.init()})
<div id="table_box_native" class="tableBox">
</div>
<div id="index_native" class="box tableDataBox"></div>
The issue is with .localCompare.
Following is the sample:
function test(v1, v2) {
console.log(v1.toString().localeCompare(v2.toString()))
}
test(1, 8)
test(1, 10)
test(8, 1)
test(8, 10) // This returns 1 instead of -1
test(10, 1)
test(10, 8)
Since you have numeric values,its always better to convert values to number and process it.
tr = tr.sort(function(a, b) { // sort rows
var v1 = a.cells[col].textContent.trim();
var v2 = b.cells[col].textContent.trim()
return reverse * (v1 - v2);
});
Sample:
myTableObjData = {
'head': ['s.no', 'name', 'per%', 'price'],
'body': [
[1, 'rohit', '9%', 23],
[10, 'rohit azad', '19%', 230],
[8, 'rohit', '39%', 111],
]
}
var _tableCustomFun = {
create_sample_table: function(parentNode, head, body, foot, data) {
if (typeof head == "undefined") {
head = true;
}
if (typeof body == "undefined") {
body = true;
}
if (typeof foot == "undefined") {
foot = true;
}
data = myTableObjData;
var table = document.createElement("table");
var tr, th, td;
// header
tr = document.createElement("tr");
var headers = data.head || [];
for (var i = 0; i < headers.length; i++) {
th = document.createElement("th");
span = document.createElement("span");
span.innerHTML = headers[i];
th.appendChild(span);
tr.appendChild(th);
}
if (head) {
var thead = document.createElement("thead");
thead.appendChild(tr);
table.appendChild(thead);
} else {
table.appendChild(tr);
}
// end header
// body
var table_body = data.body || [];
if (body) {
var tbody = document.createElement("tbody");
}
for (var i = 0; i < table_body.length; i++) {
tr = document.createElement("tr");
for (var j = 0; j < table_body[i].length; j++) {
td = document.createElement("td");
td.innerHTML = table_body[i][j];
tr.appendChild(td);
}
if (body) {
tbody.appendChild(tr);
} else {
table.appendChild(tr);
}
}
if (body) {
table.appendChild(tbody);
}
// end body
if (parentNode) {
parentNode.innerHTML = "";
parentNode.appendChild(table);
}
//return table;
},
paginator: function(config) {
// throw errors if insufficient parameters were given
if (typeof config != "object")
throw "Paginator was expecting a config object!";
if (typeof config.get_rows != "function" && !(config.table instanceof Element))
throw "Paginator was expecting a table or get_row function!";
// get/set if things are disabled
if (typeof config.disable == "undefined") {
config.disable = false;
}
// get/make an element for storing the page numbers in
var box;
if (!(config.box instanceof Element)) {
config.box = document.createElement("div");
}
box = config.box;
// get/make function for getting table's rows
if (typeof config.get_rows != "function") {
config.get_rows = function() {
var table = config.table
var tbody = table.getElementsByTagName("tbody")[0] || table;
// get all the possible rows for paging
// exclude any rows that are just headers or empty
children = tbody.children;
var trs = [];
for (var i = 0; i < children.length; i++) {
if (children[i].nodeType = "tr") {
if (children[i].getElementsByTagName("td").length > 0) {
trs.push(children[i]);
}
}
}
return trs;
}
}
var get_rows = config.get_rows;
var trs = get_rows();
// get/set rows per page
if (typeof config.rows_per_page == "undefined") {
var selects = box.getElementsByTagName("select");
if (typeof selects != "undefined" && (selects.length > 0 && typeof selects[0].selectedIndex != "undefined")) {
config.rows_per_page = selects[0].options[selects[0].selectedIndex].value;
} else {
config.rows_per_page = 150;
}
}
var rows_per_page = config.rows_per_page;
// get/set current page
if (typeof config.page == "undefined") {
config.page = 1;
}
var page = config.page;
// get page count
var pages = (rows_per_page > 0) ? Math.ceil(trs.length / rows_per_page) : 1;
// check that page and page count are sensible values
if (pages < 1) {
pages = 1;
}
if (page > pages) {
page = pages;
}
if (page < 1) {
page = 1;
}
config.page = page;
// hide rows not on current page and show the rows that are
for (var i = 0; i < trs.length; i++) {
if (typeof trs[i]["data-display"] == "undefined") {
trs[i]["data-display"] = trs[i].style.display || "";
}
if (rows_per_page > 0) {
if (i < page * rows_per_page && i >= (page - 1) * rows_per_page) {
trs[i].style.display = trs[i]["data-display"];
} else {
// Only hide if pagination is not disabled
if (!config.disable) {
trs[i].style.display = "none";
} else {
trs[i].style.display = trs[i]["data-display"];
}
}
} else {
trs[i].style.display = trs[i]["data-display"];
}
}
// page button maker functions
config.active_class = config.active_class || "active";
if (typeof config.box_mode != "function" && config.box_mode != "list" && config.box_mode != "buttons") {
config.box_mode = "button";
}
if (typeof config.box_mode == "function") {
config.box_mode(config);
} else {
var make_button;
if (config.box_mode == "list") {
make_button = function(symbol, index, config, disabled, active) {
var li = document.createElement("li");
var a = document.createElement("a");
a.href = "#";
a.innerHTML = symbol;
a.addEventListener("click", function(event) {
event.preventDefault();
this.parentNode.click();
return false;
}, false);
li.appendChild(a);
var classes = [];
if (disabled) {
classes.push("disabled");
}
if (active) {
classes.push(config.active_class);
}
li.className = classes.join(" ");
li.addEventListener("click", function() {
if (this.className.split(" ").indexOf("disabled") == -1) {
config.page = index;
_tableCustomFun.paginator(config);
}
}, false);
return li;
}
} else {
make_button = function(symbol, index, config, disabled, active) {
var button = document.createElement("button");
button.innerHTML = symbol;
button.addEventListener("click", function(event) {
event.preventDefault();
if (this.disabled != true) {
config.page = index;
_tableCustomFun.paginator(config);
}
return false;
}, false);
if (disabled) {
button.disabled = true;
}
if (active) {
button.className = config.active_class;
}
return button;
}
}
// make page button collection
var page_box = document.createElement(config.box_mode == "list" ? "ul" : "div");
if (config.box_mode == "list") {
page_box.className = "pagination";
}
var left = make_button("«", (page > 1 ? page - 1 : 1), config, (page == 1), false);
page_box.appendChild(left);
for (var i = 1; i <= pages; i++) {
var li = make_button(i, i, config, false, (page == i));
page_box.appendChild(li);
}
var right = make_button("»", (pages > page ? page + 1 : page), config, (page == pages), false);
page_box.appendChild(right);
if (box.childNodes.length) {
while (box.childNodes.length > 1) {
box.removeChild(box.childNodes[0]);
}
box.replaceChild(page_box, box.childNodes[0]);
} else {
box.appendChild(page_box);
}
}
// make rows per page selector
if (!(typeof config.page_options == "boolean" && !config.page_options)) {
if (typeof config.page_options == "undefined") {
config.page_options = [{
value: 10,
text: '10'
},
{
value: 20,
text: '20'
},
{
value: 50,
text: '50'
},
{
value: 100,
text: '100'
},
{
value: 0,
text: 'All'
}
];
}
var options = config.page_options;
var select = document.createElement("select");
for (var i = 0; i < options.length; i++) {
var o = document.createElement("option");
o.value = options[i].value;
o.text = options[i].text;
select.appendChild(o);
}
select.value = rows_per_page;
select.addEventListener("change", function() {
config.rows_per_page = this.value;
_tableCustomFun.paginator(config);
}, false);
box.appendChild(select);
}
// status message
var stat = document.createElement("span");
stat.innerHTML = "On page " + page + " of " + pages +
", showing rows " + (((page - 1) * rows_per_page) + 1) +
" to " + (trs.length < page * rows_per_page || rows_per_page == 0 ? trs.length : page * rows_per_page) +
" of " + trs.length;
box.appendChild(stat);
// hide pagination if disabled
if (config.disable) {
if (typeof box["data-display"] == "undefined") {
box["data-display"] = box.style.display || "";
}
box.style.display = "none";
} else {
if (box.style.display == "none") {
box.style.display = box["data-display"] || "";
}
}
// run tail function
if (typeof config.tail_call == "function") {
config.tail_call(config);
}
return box;
},
sortTable: function(table, col, reverse) {
_tableCustomFun.addShortingClass(table, col, reverse);
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function(a, b) { // sort rows
var v1 = a.cells[col].textContent.trim();
var v2 = b.cells[col].textContent.trim()
return reverse * (v1 - v2 );
});
for (i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
},
makeSortable: function(table) {
var th = table.tHead,
i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0)(function(i) {
var dir = 1;
th[i].addEventListener('click', function() {
_tableCustomFun.sortTable(table, i, (dir = 1 - dir))
});
}(i));
},
makeAllSortable: function(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'),
i = t.length;
while (--i >= 0) _tableCustomFun.makeSortable(t[i]);
},
addShortingClass: function(table, col, reverse) {
var thPosition = table.tHead.rows[0].cells[col];
console.log(reverse);
console.log(thPosition);
var _thead = table.tHead.rows[0]
for (var i = 0; i < _thead.cells.length; i++) {
_thead.cells[i].removeAttribute("class");
}
thPosition.classList.add("shorting");
if (reverse == 1) {
thPosition.classList.add("up");
} else {
thPosition.classList.add("down");
}
},
init: function() {
var tableNode = document.getElementById("table_box_native");
if (tableNode) {
_tableCustomFun.addCssFile();
_tableCustomFun.create_sample_table(document.getElementById("table_box_native"));
_tableCustomFun.paginator({
table: document.getElementById("table_box_native").getElementsByTagName("table")[0],
box: document.getElementById("index_native"),
active_class: "color_page"
});
_tableCustomFun.makeAllSortable();
}
},
addCssFile: function() {
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!document.getElementById(cssId)) {
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'css_tablecustom.cms?v=7&minify=1';
link.media = 'all';
head.appendChild(link);
}
}
}
// window.onload = function () {
// _tableCustomFun.init();
// };
document.addEventListener('DOMContentLoaded', function() {
_tableCustomFun.init()
})
<div id="table_box_native" class="tableBox">
</div>
<div id="index_native" class="box tableDataBox"></div>
You have to sort the table based on columns data type (number and string). You can do so by checking the column index:
.......
tr = tr.sort(function (a, b) { // sort rows
if(col == 0 || col == 3){
return reverse * (+a.cells[col].textContent.trim() - +b.cells[col].textContent.trim());
}
else{
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
}
});
........
myTableObjData = {
'head':['s.no', 'name', 'per%', 'price'],
'body': [
[1,'rohit', '9%', 23],
[10,'rohit azad', '19%', 230],
[8,'rohit', '39%', 111],
]
}
var _tableCustomFun = {
create_sample_table: function(parentNode, head, body, foot, data) {
if (typeof head == "undefined") {head = true;}
if (typeof body == "undefined") {body = true;}
if (typeof foot == "undefined") {foot = true;}
data = myTableObjData;
var table = document.createElement("table");
var tr, th, td;
// header
tr = document.createElement("tr");
var headers = data.head || [];
for (var i=0;i<headers.length;i++) {
th = document.createElement("th");
span = document.createElement("span");
span.innerHTML = headers[i];
th.appendChild(span);
tr.appendChild(th);
}
if (head) {
var thead = document.createElement("thead");
thead.appendChild(tr);
table.appendChild(thead);
} else {
table.appendChild(tr);
}
// end header
// body
var table_body = data.body || [];
if (body) {
var tbody = document.createElement("tbody");
}
for (var i=0;i<table_body.length;i++) {
tr = document.createElement("tr");
for (var j=0;j<table_body[i].length;j++) {
td = document.createElement("td");
td.innerHTML = table_body[i][j];
tr.appendChild(td);
}
if (body) {
tbody.appendChild(tr);
} else {
table.appendChild(tr);
}
}
if (body) {
table.appendChild(tbody);
}
// end body
if (parentNode) {
parentNode.innerHTML = "";
parentNode.appendChild(table);
}
//return table;
},
paginator: function(config) {
// throw errors if insufficient parameters were given
if (typeof config != "object")
throw "Paginator was expecting a config object!";
if (typeof config.get_rows != "function" && !(config.table instanceof Element))
throw "Paginator was expecting a table or get_row function!";
// get/set if things are disabled
if (typeof config.disable == "undefined") {
config.disable = false;
}
// get/make an element for storing the page numbers in
var box;
if (!(config.box instanceof Element)) {
config.box = document.createElement("div");
}
box = config.box;
// get/make function for getting table's rows
if (typeof config.get_rows != "function") {
config.get_rows = function () {
var table = config.table
var tbody = table.getElementsByTagName("tbody")[0]||table;
// get all the possible rows for paging
// exclude any rows that are just headers or empty
children = tbody.children;
var trs = [];
for (var i=0;i<children.length;i++) {
if (children[i].nodeType = "tr") {
if (children[i].getElementsByTagName("td").length > 0) {
trs.push(children[i]);
}
}
}
return trs;
}
}
var get_rows = config.get_rows;
var trs = get_rows();
// get/set rows per page
if (typeof config.rows_per_page == "undefined") {
var selects = box.getElementsByTagName("select");
if (typeof selects != "undefined" && (selects.length > 0 && typeof selects[0].selectedIndex != "undefined")) {
config.rows_per_page = selects[0].options[selects[0].selectedIndex].value;
} else {
config.rows_per_page = 150;
}
}
var rows_per_page = config.rows_per_page;
// get/set current page
if (typeof config.page == "undefined") {
config.page = 1;
}
var page = config.page;
// get page count
var pages = (rows_per_page > 0)? Math.ceil(trs.length / rows_per_page):1;
// check that page and page count are sensible values
if (pages < 1) {
pages = 1;
}
if (page > pages) {
page = pages;
}
if (page < 1) {
page = 1;
}
config.page = page;
// hide rows not on current page and show the rows that are
for (var i=0;i<trs.length;i++) {
if (typeof trs[i]["data-display"] == "undefined") {
trs[i]["data-display"] = trs[i].style.display||"";
}
if (rows_per_page > 0) {
if (i < page*rows_per_page && i >= (page-1)*rows_per_page) {
trs[i].style.display = trs[i]["data-display"];
} else {
// Only hide if pagination is not disabled
if (!config.disable) {
trs[i].style.display = "none";
} else {
trs[i].style.display = trs[i]["data-display"];
}
}
} else {
trs[i].style.display = trs[i]["data-display"];
}
}
// page button maker functions
config.active_class = config.active_class||"active";
if (typeof config.box_mode != "function" && config.box_mode != "list" && config.box_mode != "buttons") {
config.box_mode = "button";
}
if (typeof config.box_mode == "function") {
config.box_mode(config);
} else {
var make_button;
if (config.box_mode == "list") {
make_button = function (symbol, index, config, disabled, active) {
var li = document.createElement("li");
var a = document.createElement("a");
a.href = "#";
a.innerHTML = symbol;
a.addEventListener("click", function (event) {
event.preventDefault();
this.parentNode.click();
return false;
}, false);
li.appendChild(a);
var classes = [];
if (disabled) {
classes.push("disabled");
}
if (active) {
classes.push(config.active_class);
}
li.className = classes.join(" ");
li.addEventListener("click", function () {
if (this.className.split(" ").indexOf("disabled") == -1) {
config.page = index;
_tableCustomFun.paginator(config);
}
}, false);
return li;
}
} else {
make_button = function (symbol, index, config, disabled, active) {
var button = document.createElement("button");
button.innerHTML = symbol;
button.addEventListener("click", function (event) {
event.preventDefault();
if (this.disabled != true) {
config.page = index;
_tableCustomFun.paginator(config);
}
return false;
}, false);
if (disabled) {
button.disabled = true;
}
if (active) {
button.className = config.active_class;
}
return button;
}
}
// make page button collection
var page_box = document.createElement(config.box_mode == "list"?"ul":"div");
if (config.box_mode == "list") {
page_box.className = "pagination";
}
var left = make_button("«", (page>1?page-1:1), config, (page == 1), false);
page_box.appendChild(left);
for (var i=1;i<=pages;i++) {
var li = make_button(i, i, config, false, (page == i));
page_box.appendChild(li);
}
var right = make_button("»", (pages>page?page+1:page), config, (page == pages), false);
page_box.appendChild(right);
if (box.childNodes.length) {
while (box.childNodes.length > 1) {
box.removeChild(box.childNodes[0]);
}
box.replaceChild(page_box, box.childNodes[0]);
} else {
box.appendChild(page_box);
}
}
// make rows per page selector
if (!(typeof config.page_options == "boolean" && !config.page_options)) {
if (typeof config.page_options == "undefined") {
config.page_options = [
{ value: 10, text: '10' },
{ value: 20, text: '20' },
{ value: 50, text: '50' },
{ value: 100,text: '100' },
{ value: 0, text: 'All' }
];
}
var options = config.page_options;
var select = document.createElement("select");
for (var i=0;i<options.length;i++) {
var o = document.createElement("option");
o.value = options[i].value;
o.text = options[i].text;
select.appendChild(o);
}
select.value = rows_per_page;
select.addEventListener("change", function () {
config.rows_per_page = this.value;
_tableCustomFun.paginator(config);
}, false);
box.appendChild(select);
}
// status message
var stat = document.createElement("span");
stat.innerHTML = "On page " + page + " of " + pages
+ ", showing rows " + (((page-1)*rows_per_page)+1)
+ " to " + (trs.length<page*rows_per_page||rows_per_page==0?trs.length:page*rows_per_page)
+ " of " + trs.length;
box.appendChild(stat);
// hide pagination if disabled
if (config.disable) {
if (typeof box["data-display"] == "undefined") {
box["data-display"] = box.style.display||"";
}
box.style.display = "none";
} else {
if (box.style.display == "none") {
box.style.display = box["data-display"]||"";
}
}
// run tail function
if (typeof config.tail_call == "function") {
config.tail_call(config);
}
return box;
},
sortTable: function(table, col, reverse) {
_tableCustomFun.addShortingClass(table, col, reverse);
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
if(col == 0 || col == 3){
return reverse * (+a.cells[col].textContent.trim() - +b.cells[col].textContent.trim());
}
else{
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
}
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
},
makeSortable: function(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {_tableCustomFun.sortTable(table, i, (dir = 1 - dir))});
}(i));
},
makeAllSortable: function(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) _tableCustomFun.makeSortable(t[i]);
},
addShortingClass: function(table, col, reverse){
var thPosition = table.tHead.rows[0].cells[col];
//console.log(reverse);
//console.log(thPosition);
var _thead = table.tHead.rows[0]
for (var i = 0; i < _thead.cells.length; i++) {
_thead.cells[i].removeAttribute("class");
}
thPosition.classList.add("shorting");
if(reverse == 1){
thPosition.classList.add("up");
}else{
thPosition.classList.add("down");
}
},
init: function(){
var tableNode = document.getElementById("table_box_native");
if(tableNode){
_tableCustomFun.addCssFile();
_tableCustomFun.create_sample_table(document.getElementById("table_box_native"));
_tableCustomFun.paginator({
table: document.getElementById("table_box_native").getElementsByTagName("table")[0],
box: document.getElementById("index_native"),
active_class: "color_page"
});
_tableCustomFun.makeAllSortable();
}
},
addCssFile: function(){
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'css_tablecustom.cms?v=7&minify=1';
link.media = 'all';
head.appendChild(link);
}
}
}
// window.onload = function () {
// _tableCustomFun.init();
// };
document.addEventListener('DOMContentLoaded', function(){_tableCustomFun.init()})
<div id="table_box_native" class="tableBox">
</div>
<div id="index_native" class="box tableDataBox"></div>
There is a strange behavior with DOMParser. When I use "text/xml" as the parameter I get my object and each time I use a child (like parentNodes), the child is itself a DOM object. However, when I use "text/html" as the parameter, the children are not DOM objects. Why is that and how can I have DOM objects for all the children?
Here is what I do:
parser = new DOMParser();
doc = parser.parseFromString(stringContainingHTMLSource, "text/html").getElementsByTagName('p');
console.log(doc[0].childNodes[0]);
My childNode returns the element but not as a DOM object...
Edit:
Here are my recursive functions:
var getParents = function(node, parentNodes){
if(node.nodeName == 'span'){
parentNodes.push(node.attributes[0].nodeValue);
} else if(node.nodeName == 'p' && node.attributes.length > 0) {
parentNodes.push(node.nodeName);
parentNodes.push(node.attributes[0].nodeValue);
} else {
parentNodes.push(node.nodeName);
}
if(node.parentNode.nodeName != '#document'){
getParents(node.parentNode, parentNodes);
}
return parentNodes;
};
var parse = function(node, vertical, horizontal, paragraph){
if(node.childNodes.length > 0){
for(var int = 0; int < node.childNodes.length; int++){
parse(node.childNodes[int], vertical, horizontal, paragraph);
}
} else{
var object = {};
var attributes = getParents(node, []);
for(var int = 0; int < attributes.length; int++) {
// right alignment
if(/text-align/i.test(attributes[int])){
object.alignment = attributes[int].split(": ")[1].replace(';','');
} else if (/color/i.test(attributes[int])) {
// color
object.color = attributes[int].split(":")[1];
} else if (attributes[int] == 'em') {
// italic
if (object.italics) {
delete object.bold;
object.bolditalics = true;
} else {
object.italics = true;
}
} else if (attributes[int] == 'strong') {
// bold
if (object.italics) {
delete object.italics;
object.bolditalics = true;
} else {
object.bold = true;
}
} else if (attributes[int] == 'u') {
// underline
object.decoration = 'underline';
} else if (attributes[int] == 's') {
// strike
object.decoration = 'lineThrough';
}
}
object.text = node.textContent;
pdfContent[vertical][horizontal].push(object);
}
};
for(var vertical = 0; vertical < payment.htmlContent.length; vertical++) {
for(var horizontal = 0; horizontal < payment.htmlContent[vertical].length; horizontal++) {
var parser = new DOMParser();
var paragraphs = parser.parseFromString(payment.htmlContent[vertical][horizontal], "text/xml").getElementsByTagName('p');
for (var paragraph = 0; paragraph < paragraphs.length; paragraph++) {
for (var num = 0; num < paragraphs[paragraph].childNodes.length; num++) {
parse(paragraphs[paragraph].childNodes[num], vertical, horizontal, paragraph);
}
}
}
}
I made a few assumptions on what the values are and after I Added a few verifications like if(node.attributes.length>0)into your code, it seems to work.
var payment={htmlContent:[['<p>some<em>text</em></p>', '<p>some<span>text<strong>here</strong></span></p>'],['<p>some<s>text</s></p>', '<p>some<span style="color:#FF00FF">text</span></p>']]};
var getParents = function(node, parentNodes){
if(node.nodeName == 'span'){
if(node.attributes.length>0)
parentNodes.push(node.attributes[0].nodeValue);
} else if(node.nodeName == 'p' && node.attributes.length > 0) {
parentNodes.push(node.nodeName);
if(node.attributes.length>0)
parentNodes.push(node.attributes[0].nodeValue);
} else {
parentNodes.push(node.nodeName);
}
if(node.parentNode.nodeName != '#document'){
getParents(node.parentNode, parentNodes);
}
return parentNodes;
};
var parse = function(node, vertical, horizontal, paragraph){
if(node.childNodes.length > 0){
for(var int = 0; int < node.childNodes.length; int++){
parse(node.childNodes[int], vertical, horizontal, paragraph);
}
} else{
var object = {};
var attributes = getParents(node, []);
console.log(attributes);
for(var int = 0; int < attributes.length; int++) {
// right alignment
if(/text-align/i.test(attributes[int])){
object.alignment = attributes[int].split(": ")[1].replace(';','');
} else if (/color/i.test(attributes[int])) {
// color
object.color = attributes[int].split(":")[1];
} else if (attributes[int] == 'em') {
// italic
if (object.italics) {
delete object.bold;
object.bolditalics = true;
} else {
object.italics = true;
}
} else if (attributes[int] == 'strong') {
// bold
if (object.italics) {
delete object.italics;
object.bolditalics = true;
} else {
object.bold = true;
}
} else if (attributes[int] == 'u') {
// underline
object.decoration = 'underline';
} else if (attributes[int] == 's') {
// strike
object.decoration = 'lineThrough';
}
}
object.text = node.textContent;
if(!pdfContent[vertical])pdfContent[vertical]=[];
if(!pdfContent[vertical][horizontal])
pdfContent[vertical][horizontal]=[];
pdfContent[vertical][horizontal].push(object);
}
};
var pdfContent = [];
for(var vertical = 0; vertical < payment.htmlContent.length; vertical++) {
for(var horizontal = 0; horizontal < payment.htmlContent[vertical].length; horizontal++) {
var parser = new DOMParser();
var paragraphs = parser.parseFromString(payment.htmlContent[vertical][horizontal], "text/xml").getElementsByTagName('p');
for (var paragraph = 0; paragraph < paragraphs.length; paragraph++) {
for (var num = 0; num < paragraphs[paragraph].childNodes.length; num++) {
parse(paragraphs[paragraph].childNodes[num], vertical, horizontal, paragraph);
}
}
}
}
for(var i=0; i<pdfContent.length; i++){
for(var j=0; j<pdfContent[i].length; j++){
document.querySelector('#log').textContent+=pdfContent[i][j].toSource();
}
}
<p id="log"></p>