Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript getElementById and convert it to String

Tags:

javascript

is there a way to convert a javascript HTML object to a string? i.e.

var someElement = document.getElementById("id");
var someElementToString = someElement.toString();

thanks a lot in advance

like image 578
bombo Avatar asked Mar 18 '10 13:03

bombo


People also ask

How do I return a getElementById document?

Document.getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

What is the getElementById () function?

The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.

What is difference between getElementById and Getelementsbyname?

The difference is that GetElementByID() will retrieve a single element object based on the unique id specified, whereas GetElementsByTagName() will retrieve an array of all element objects with the specified tag name. Then you can obtain the value using GetElementById from your C++ code.

Why is getElementById returning NULL?

This error TypeError: document. getelementbyid(...) is null would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element.


1 Answers

If you want a string representation of the entire tag then you can use outerHTML for browsers that support it:

var someElementToString = someElement.outerHTML;

For other browsers, apparently you can use XMLSerializer:

var someElement = document.getElementById("id");
var someElementToString;

if (someElement.outerHTML)
    someElementToString = someElement.outerHTML;
else if (XMLSerializer)
    someElementToString = new XMLSerializer().serializeToString(someElement); 
like image 119
Andy E Avatar answered Sep 23 '22 16:09

Andy E