How to do element extraction in javascript?

I have placeholder with any web page url. It should extract the elements when i click on button. I have to show elements and xpath values in my page. How can i do that? Please help me.

I am not able to get node values and i am not able to append to innerHtml of other web page.
My code follows


function buildDom(text) {
    var div = document.createElement('div');
    div.innerHTML = text;
    return div.firstChild;
}

function fetchAttrs(node) { // getting attributes object for element
    return node && Array.prototype.reduce.call(node.attributes, function(list, attribute) {
            list[attribute.name] = attribute.value;
            return list;
        }, {}) || {};
}

function traverseElement(element,argPrefix) {
    if (element.nodeType === Node.TEXT_NODE)
        return; // skipping text elements

    var attrs = fetchAttrs(element);
    var prefix = argPrefix + "/" + element.tagName; // build element path
    if (Object.keys(attrs).length !== 0){
        prefix += "[" + Object.keys(attrs).map(value, function () {
                return "@" + value + ' = "' + attrs[value] + '"'
            }).join(" and ") + "]"; // append arguments
    }

    console.log(prefix);

    var children = element.childNodes ;// iterating over children
    for (var i = 0; i < children.length; i++)
    {
        traverseElement(children[i], prefix)
    }
}

function extractElements(){
    var url = document.getElementById('webUrlId').value;
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {// when loaded
            
            var dom = buildDom(this.responseText);

            traverseElement(dom) ;// and traverse it
        }
    };
    xhttp.open("GET", url, true);
    xhttp.send();

}



We need to see the HTML that interacts with as well.

yeah. sure.

<input id="webUrlId" type="text" placeholder="Enter web url">
<button type="button"
        onclick="extractElements();">Extract</button>

<div id="demo"></div>

Do you take Same-origin policy into account?

This is sample view that i want to extract

https://lh3.googleusercontent.com/-XaRhcImsmsM/V-tmdXrhNoI/AAAAAAAAAAs/EPhzRn5iikQ3-FAei0VV0ifkpJaHrJCewCL0B/h303/Untitled%2Bpicture.png

No @megazoid. we can do in chrome. CORS is not a problem

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.