In image it is a jQuery object which you can create using following code
var a = '<div id="foo">\
<h1 class="greeting">Hello World!</h1>\
</div>';
var aDom = jQuery(a);
console.log(aDom );
Pure JavaScript: jsfiddle
var e = document.createElement("div");
e.id = "foo";
e.innerHTML = '<h1 class="greeting">Hello World!</h1>';
console.log(e);
Answer from Anoop on Stack OverflowIn image it is a jQuery object which you can create using following code
var a = '<div id="foo">\
<h1 class="greeting">Hello World!</h1>\
</div>';
var aDom = jQuery(a);
console.log(aDom );
Pure JavaScript: jsfiddle
var e = document.createElement("div");
e.id = "foo";
e.innerHTML = '<h1 class="greeting">Hello World!</h1>';
console.log(e);
Edited
var a = '<div id="test"></div>';
var htmlObject = document.createElement('div');
htmlObject.innerHTML = a;
htmlObject.getElementById("test") = data;
» npm install html-to-object
convert HTML DOM element to JavaScript Object? - Stack Overflow
javascript - Convert object to HTML element - Stack Overflow
converting a javascript string to a html object - Stack Overflow
Transform html into object in Javascript - Stack Overflow
is there an alternative method I can use to view it and it's properties as a JavaScript object instead rather than a html element?
all I want to do is get the element, not do any parsing and build something new and ideally in dev tools
Yes if you are only interested in the dev tools (console), you can always use console.dir() method, it's made for this:
console.dir(document.getElementById('myid'));
console.dir() method:
Displays an interactive list of the properties of the specified JavaScript object. The output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.
Would do something like using the Document Element interface to access the array of attributes / properties.
Use addEventListener to register events on Element and .bind(thisArg) to have specified argument as this-context
var elemen = {
tag: 'a',
content: "blabal",
attr: {
href: "vk.com",
id: 'someId'
},
events: {
click: 'alert(this.href)',
focus: 'this.className="active"'
}
};
var node = document.createElement(elemen.tag);
node.innerHTML = elemen.content;
for (var attr in elemen.attr) {
node.setAttribute(attr, elemen.attr[attr]);
}
for (var prop in elemen.events) {
node.addEventListener(prop, new Function(elemen.events[prop]).bind(node));
}
document.body.appendChild(node);
.active {
color: red;
}
Using only javascript
var _createElem = document.createElement(""+_elem.tag+"");
_createElem.innerHTML = _elem.content;
//set attributes
for(var keys in _elem.attr){
_createElem.setAttribute(''+keys+'',_elem.attr[keys])
}
//set style
for(var keys in _elem.style){
_createElem.setAttribute(''+keys+'',_elem.style[keys])
}
//set events
for(var keys in _elem.events){
_createElem.setAttribute('on'+keys,_elem.events[keys])
}
document.getElementById("demoDiv").appendChild(_createElem)
Note: The elem has got both onclick & href , you may need to return true/false as per your requirement
var s = '<div id="myDiv"></div>';
var htmlObject = document.createElement('div');
htmlObject.innerHTML = s;
htmlObject.getElementById("myDiv").style.marginTop = something;
You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..
string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call
but still, it would not be found by the getElementById because for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.
You would need to use append or appendTo or after etc.. to put it in the dom first..
Of'course all these can be done through regular javascript but it would take more steps to accomplish the same thing... and the logic is the same in both cases..
You can use recursion. And this seems a good case for a generator function. As it was not clear which tags should be retained in format (apparently, not p), I left this as a configuration to provide:
const formatTags = new Set(["b", "big", "code", "del", "em", "i", "pre", "s", "small", "strike", "strong", "sub", "sup", "u"]);
function* iterLeafNodes(nodes, format=[]) {
for (let node of nodes) {
if (node.nodeType == 3) {
yield ({text: node.nodeValue, format: format.length ? [...format] : null});
} else {
const tag = node.tagName.toLowerCase();
yield* iterLeafNodes(node.childNodes,
formatTags.has(tag) ? format.concat(tag) : format);
}
}
}
// Example input
const strHTML = "<p>Hello World</p><p>I am a text with <strong>bold</strong> word</p><p><strong>I am bold text with nested <em>italic</em> Word.</strong></p>"
const nodes = new DOMParser().parseFromString(strHTML, 'text/html').body.childNodes;
let result = [...iterLeafNodes(nodes)];
console.log(result);
Note that this will still split the text when it is spread over multiple tags, which are considered non-formatting tags, like span.
Secondly, I'm not convinced that having null as a possible value for format is more useful then just an empty array [], but anyway, the above produces null in that case.
Special case - insertion of \n
In comments you ask for the insertion of a line break after each p element.
The code below will generate that extra element. Here I also used [] instead of null for format:
const formatTags = new Set(["b", "big", "code", "del", "em", "i", "pre", "s", "small", "strike", "strong", "sub", "sup", "u"]);
function* iterLeafNodes(nodes, format=[]) {
for (let node of nodes) {
if (node.nodeType == 3) {
yield ({text: node.nodeValue, format: [...format]});
} else {
const tag = node.tagName.toLowerCase();
yield* iterLeafNodes(node.childNodes,
formatTags.has(tag) ? format.concat(tag) : format);
if (tag === "p") yield ({text: "\n", format: [...format]});
}
}
}
// Example input
const strHTML = "<p>Hello World</p><p>I am a text with <strong>bold</strong> word</p><p><strong>I am bold text with nested <em>italic</em> Word.</strong></p>"
const nodes = new DOMParser().parseFromString(strHTML, 'text/html').body.childNodes;
let result = [...iterLeafNodes(nodes)];
console.log(result);
You can recursively loop over the child nodes and construct the desired array using an array like FORMAT_NODES.
const FORMAT_NODES = ["strong", "em"];
function getText(node, parents = [], res = []) {
if (node.nodeName === "#text") {
const text = node.textContent.trim();
if (text) {
const format = parents.filter((p) => FORMAT_NODES.includes(p));
res.push({ text, format: format.length ? format : null });
}
} else {
node.childNodes.forEach((node) =>
getText(node, parents.concat(node.nodeName.toLowerCase()), res)
);
}
return res;
}
const container = document.querySelector("#container");
const result = getText(container);
console.log(result);
<div id="container">
<p>Hello World</p>
<p>I am a text with <strong>bold</strong> word</p>
<p><strong>I am bold text with nested <em>italic</em> Word.</strong></p>
</div>
Relevant Documentations:
- Node.childNodes
- Node.parentNode
- Array.prototype.concat
- Array.prototype.includes
var tbl = $('#students tr:has(td)').map(function(i, v) {
var $td = $('td', this);
return {
id: ++i,
name: $td.eq(0).text(),
age: $td.eq(1).text(),
grade: $td.eq(2).text()
}
}).get();
→
I needed this exact thing, except I needed more features to be able to override column names and ignore any hidden rows. I wrote a jQuery plugin that does just that, located here https://github.com/lightswitch05/table-to-json
for your example you would do: (http://jsfiddle.net/ptVDm/118/)
var table = $('#students').tableToJSON();
One thing to note is that the id's aren't part of the resulting object. You could just get the id from the object's array location. Or if you really needed it to be part of the object, you could create an hidden column for the ID's and then they would be included
Hello,
I'm working on a horrible site that I can't control that presents relevant data I need to scrape in the form of a HTML table. As a version 1, I've collected the data I used with specific indexes. But seeing as that's more fragile than not, I would like to iterate upon this code I found.
Goal: Skip over blank table data cells and only collect table cells with data and be able to make a key:value pair with the table header cell if there is one.
Original Source:https://stackoverflow.com/questions/9927126/how-to-convert-the-following-table-to-json-with-javascript Source: http://jsfiddle.net/s4tyk/
var myRows = [];
var headersText = [];
var $headers = $("th");
// Loop through grabbing everything
var $rows = $("tbody tr").each(function(index) {
$cells = $(this).find("td");
myRows[index] = {};
$cells.each(function(cellIndex) {
// Set the header text
if(headersText[cellIndex] === undefined) {
headersText[cellIndex] = $($headers[cellIndex]).text();
}
// Update the row object with the header/cell combo
myRows[index][headersText[cellIndex]] = $(this).text();
});
});
// Let's put this in the object like you want and convert to JSON (Note: jQuery will also do this for you on the Ajax
request)
var myObj = {
"myrows": myRows
};
alert(JSON.stringify(myObj)); The problem arises where I have a lot of empty table cells which then gives me some empty keys.
Example Table
| whitespace | Center align | whitespace |
|---|---|---|
| This | No Data | This |
| column | column | No Data |
| will | No Data | will |
| be | be | No Data |
| left | center | right |
| No Data | aligned | aligned |
I've been console logging everything, but I'm just not getting where I would do this in the code.