Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the string representation of a DOM node

People also ask

How do I get the DOM element value?

One of the most common methods to access an element in HTML DOM is getElementById() which accesses an element based on the value of its ID attribute. The value of the ID attributes are supposed to be unique and no two elements on a single HTML page should have similar IDs.

How do I check my DOM nodes?

# Search for nodes You can search the DOM Tree by string, CSS selector, or XPath selector. Focus your cursor on the Elements panel. Press Control + F or Command + F (Mac). The Search bar opens at the bottom of the DOM Tree.

What represents every node in the DOM?

Every node in the DOM represents and HTML element.

Can you access DOM node JS?

With the HTML DOM, all nodes in the node tree can be accessed by JavaScript. New nodes can be created, and all nodes can be modified or deleted.


You can create a temporary parent node, and get the innerHTML content of it:

var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));

var tmp = document.createElement("div");
tmp.appendChild(el);
console.log(tmp.innerHTML); // <p>Test</p>

EDIT: Please see answer below about outerHTML. el.outerHTML should be all that is needed.


What you're looking for is 'outerHTML', but wee need a fallback coz it's not compatible with old browsers.

var getString = (function() {
  var DIV = document.createElement("div");

  if ('outerHTML' in DIV)
    return function(node) {
      return node.outerHTML;
    };

  return function(node) {
    var div = DIV.cloneNode();
    div.appendChild(node.cloneNode(true));
    return div.innerHTML;
  };

})();

// getString(el) == "<p>Test</p>"

You'll find my jQuery plugin here: Get selected element's outer HTML


I dont think you need any complicated script for this. Just use

get_string=(el)=>el.outerHTML;

Under FF you can use the XMLSerializer object to serialize XML into a string. IE gives you an xml property of a node. So you can do the following:

function xml2string(node) {
   if (typeof(XMLSerializer) !== 'undefined') {
      var serializer = new XMLSerializer();
      return serializer.serializeToString(node);
   } else if (node.xml) {
      return node.xml;
   }
}