Reputation: 135
I am very new to web design and development so some things might be wrong in my request. Basically, I have a web page with a bunch of span tags like this ex:
Those span tags are the part of relatively big DOM tree and have a lot of ancestors.
As I understand, web page built by reactjs. Now my question is how in an efficient way, using JavaScript only I can get those values?
If you need additional info, please, do not hesitate to ask
Upvotes: 0
Views: 1543
Reputation: 2875
First select all <span>
elements which have the attribute data-reactid
. Then you can get the reactid using .getAttribute("data-reactid")
and the value by grabbing the spans childNode:
Example code
var elements = document.querySelectorAll("span[data-reactid]");
elements.forEach(function(entry) {
console.log(entry.getAttribute("data-reactid")+ ": " + entry.childNodes[0].nodeValue);
});
PhantomJS Example
var page = require('webpage').create();
var fs = require('fs');
var url = "http://learngitbranching.js.org/?demo";
var fileName = "output";
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36';
page.settings.loadImages = false;
page.open(url, function(status) {
console.log("Status: " + status);
if(status === "success") {
var values = page.evaluate(function () {
var array = [].map.call( document.querySelectorAll('span[data-reactid]:not(:empty)'), function(value, index) {return value;});
return [].map.call(array.filter(function (value) {return (value.childNodes != undefined && value.childNodes[0].nodeType == Node.TEXT_NODE);}),
function (data) { return {reactid : data.getAttribute("data-reactid"), value : data.childNodes[0].nodeValue}; });
});
var string = "";
values.forEach(function(entry) {
string = string + entry.reactid+ ": " + entry.value + "\n";
});
var path = fileName+'.txt';
fs.write(path, string, 'w');
}
phantom.exit();
});
Upvotes: 1