Create string from HTMLDivElement - javascript

What I would like to be able to do is create a string from a Javascript HTMLElement Object. For example:
var day = document.createElement("div");
day.className = "day";
day.textContent = "Random Text";
Now we have create the day HTMLDivElement Object is it possible to make it print as a string? e.g.
<div class="day">Random Text</div>

Variant on Gump's wrapper, since his implementation lifts the target node out of the document.
function nodeToString ( node ) {
var tmpNode = document.createElement( "div" );
tmpNode.appendChild( node.cloneNode( true ) );
var str = tmpNode.innerHTML;
tmpNode = node = null; // prevent memory leaks in IE
return str;
}
To print the resulting string on screen (re: escaped)
var escapedStr = nodeToString( node ).replace( "<" , "<" ).replace( ">" , ">");
outputNode.innerHTML += escapedStr;
Note, attributes like "class" , "id" , etc being stringified properly is questionable.

You can use this function (taken from pure.js)
function outerHTML(node){
return node.outerHTML || new XMLSerializer().serializeToString(node);
}

A few years have passed since the last answers. So here is an easier approach:
I found out that .outerHTML is supported by all major browsers now (see caniuse).
You can use it to get the HTML of an JS element with ease:
// Create a sample HTMLDivElement
var Day = document.createElement("div");
Day.className = "day";
Day.textContent = "Random Text";
// Log the element's HTML to the console
console.log(Day.outerHTML)
This will log: <div class="day">Random Text</div>

You can wrap that element into another element and use innerHTML on it:
var wrapper = document.createElement("div");
wrapper.appendChild(day);
var str = wrapper.innerHTML;

You need to create text node to add text for your created element like this:
var day = document.createElement("div");
day.className = "day";
// create text node
var txt = document.createTextNode('Random Text');
// add text to div now
day.appendChild(txt);
// append to body
document.body.appendChild(day);

Why would you use createElement if you can also directly parse a string?
Like: var string = '<div class="' + class + '">' + text + '</div>';

My element was a object with element : HTMLDivElement, so this worked for me.
console.log(row.element.outerHTML);
If you have just HTMLDivElement, then this should work:
console.log(row.outerHTML);

Simple use the function outerHTML
var anc = document.createElement("a");
anc.href = "https://developer.mozilla.org?a=b&c=d";
console.log(anc.outerHTML); // output: "<a href='https://developer.mozilla.org?a=b&c=d'></a>"
know more

Related

Add HTML element inside JS variable

var $document = $(document);
var selector = '[data-rangeslider]';
var $element = $(selector);
// For ie8 support
var textContent = ('textContent' in document) ? 'textContent' : 'innerText';
// Example functionality to demonstrate a value feedback
function valueOutput(element) {
var value = element.value;
var output = element.parentNode.getElementsByTagName('output')[0] || element.parentNode.parentNode.getElementsByTagName('output')[0];
output[textContent] = value + 'mm';
}
$document.on('input', 'input[type="range"], ' + selector, function(e) {
valueOutput(e.target);
});
in the line output[textContent] = value + 'mm'; I need the output as value + '<span class="classname">mm</span>'
I tried most of the things and did a lot of research but no luck so far.
This might be something very simple but I am too new to JavaScript so couldn't figure it out.
You should change this line:
output[textContent] = value + 'mm';
to:
output.innerHTML = value + '<span>mm</span>';
Also, you could remove the IE8 fallback, as it will not be necessary. All browsers have support for innerHTML.
In your code you are assigning the node text and not the node HTML as you should.
You can read more about the difference between innerText and innerHTML here.
var textContent = ('textContent' in document) ? 'textContent' : 'innerText';
textContent and innerText are both functions for adding text to an element you want to use innerHTML to add HTML.
Like this:
ouput.innerHTML = ...;
Did you try this solution?
output.innerHTML = `${value} <span class="my-class">mm</span>`;

How to select a <div> block inside a text?

I have a text composed of two <div> inside one <body> saved as raw_text as following:
var raw_text = "<body><div>This is the 'div' text that I don't want.</div> <div>This is the 'div' text that I want to print.</div></body>";
I need a script for print on the screen only the <div> present in raw-text that include a certain string.
if the string wanted is:
var x = "that I want";
the script should take:
<div>This is the 'div' text that I want to print.</div>
and the output should be:
This is the 'div' text that I want to print.
This is the proper way to do it:
Use a DOM parser
Iterate the text nodes
Check if they contain the desired string
var html = "<body><div>This is the 'div' text that I don't want.</div> <div>This is the 'div' text that I want to print.</div></body>";
var x = "that I want";
var doc = new DOMParser().parseFromString(html, 'text/html');
var it = doc.createNodeIterator(doc.body, NodeFilter.SHOW_TEXT);
var node;
while (node = it.nextNode()) if(node.nodeValue.includes(x)) {
console.log(node.nodeValue);
break;
}
var raw_text = "<body><div>This is the 'div' text that I don't want.</div> <div>This is the 'div' text that I want to print.</div></body>";
var x = "that I want";
var homework_solution = raw_text.match(new RegExp("<div>([^<>]*?"+x+"[^<>]*?)</div>"))[1];
This should do the job. The regex could possibly be made a bit more robust.
The "proper" way to do this would be to use DOMParser to search for the node you want.
You can use jQuery to convert your string to proper DOM elements, and then parse them easily, as #Retr0spectrum says on their comment. You have the HTML in a plain string:
var htmlString = "<body><div>This is the 'div' text that I don't want.</div> <div>This is the 'div' text that I want to print.</div></body>";
Now you have to:
parse it to DOM,
filter the elements, and
get the text
Like this:
// Process the string through jQuery so it parses the DOM elements
var dom = $(htmlString);
// and then we convert to array...
var array = dom.toArray();
// ... so we can filter it, using RegEx to find the
// <div>(s) we are interested in:
var matchingDivs = array.filter(function (div, i) {
return $(div).text().match(/that I want/g) !== null;
});
// we pop the last matched div from the filtered array (the first
// one would also work, since normally you will find just one)
var theDiv = matchingDivs.pop();
// Then get the <div>'s text:
var theText = selectedDiv.textContent;
The beautiful thing is you can chain all the methods so you can write the above like this:
var theText = $(htmlString).toArray().filter(function (div, i) {
return $(div).text().match(/that I want/g) !== null;
})[0].textContent;
Note: In the chained methods example I took the first element instead of the last one, using the bracket operator [0] instead of pop().
Hope this helps understanding how it works.

inserting text-field to table cell using javascript

I am making a program in which I want to add an input field to a table cell.
Look at the code below:
var arr_title = ["song","artist","genre"];
for (var title in arr_title){
var newl = document.createElement("input");
newl.id = 'edit_text';
var newf = "td_" + arr_title[title];
newf.appendChild(newl);
}
newf gets the value of td_song,td_artist etc and these are already defined as:
var td_song = document.createElement("td");
var td_artist = document.createElement("td");
var td_genre = document.createElement("td");
in the same function and then I've appended them to a table and it works fine
but when I am creating the input element then there's an error:
Uncaught TypeError: newf.appendChild is not a function
I know it has no end tag and it needs to be in a form element, but the error is same when I try to add any other element.
Help!
the value stored in newf is a string, not a DOM element; appendChild is not a valid method on strings. Just because the string value stored in newf matches the name of a variable you created (td_song, etc), does not mean it is now a handle to that element. You would be better of storing your created elements in an object, keyed off of that value:
var elems = {
td_song: document.createElement("td"),
td_artist: document.createElement("td"),
td_genre: document.createElement("td")
};
var arr_title = ["song","artist","genre"];
for (var title in arr_title){
var newl = document.createElement("input");
newl.id = 'edit_text';
var newf = "td_" + arr_title[title];
elems[newf].appendChild(newl);
}
After this line, the contents of newf is simply a string reading "td_song" for example.
var newf = "td_" + arr_title[title];
You are probably getting a JS error of "newf is not a function" ?
If you want newf to really be the one of those vars, you could explore using eval()
var newf = eval("td_" + arr_title[title]);
Does the <td> you're trying to append to have an ID of "td_" + arr_title[title]?
If so, you need to do...
var newf = document.getElementById("td_" + arr_title[title]);
newf.appendChild(newl);
newf is a string and you can't append child to string, if you want to refer to the variable with this name you should use window :
window[newf].appendChild(newl);
Hope this helps.

jQuery Object to HTML [duplicate]

How do you convert a jQuery object into a string?
I assume you're asking for the full HTML string. If that's the case, something like this will do the trick:
$('<div>').append($('#item-of-interest').clone()).html();
This is explained in more depth here, but essentially you make a new node to wrap the item of interest, do the manipulations, remove it, and grab the HTML.
If you're just after a string representation, then go with new String(obj).
Update
I wrote the original answer in 2009. As of 2014, most major browsers now support outerHTML as a native property (see, for example, Firefox and Internet Explorer), so you can do:
$('#item-of-interest').prop('outerHTML');
With jQuery 1.6, this seems to be a more elegant solution:
$('#element-of-interest').prop('outerHTML');
Just use .get(0) to grab the native element, and get its outerHTML property:
var $elem = $('Some element');
console.log("HTML is: " + $elem.get(0).outerHTML);
Can you be a little more specific? If you're trying to get the HTML inside of a tag you can do something like this:
HTML snippet:
<p><b>This is some text</b></p>
jQuery:
var txt = $('p').html(); // Value of text is <b>This is some text</b>
The best way to find out what properties and methods are available to an HTML node (object) is to do something like:
console.log($("#my-node"));
From jQuery 1.6+ you can just use outerHTML to include the HTML tags in your string output:
var node = $("#my-node").outerHTML;
jQuery is up in here, so:
jQuery.fn.goodOLauterHTML= function() {
return $('<a></a>').append( this.clone() ).html();
}
Return all that HTML stuff:
$('div' /*elys with HTML text stuff that you want */ ).goodOLauterHTML(); // alerts tags and all
This seems to work fine for me:
$("#id")[0].outerHTML
The accepted answer doesn't cover text nodes (undefined is printed out).
This code snippet solves it:
var htmlElements = $('<p>google</p>↵↵<p>bing</p>'),
htmlString = '';
htmlElements.each(function () {
var element = $(this).get(0);
if (element.nodeType === Node.ELEMENT_NODE) {
htmlString += element.outerHTML;
}
else if (element.nodeType === Node.TEXT_NODE) {
htmlString += element.nodeValue;
}
});
alert('String html: ' + htmlString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
No need to clone and add to the DOM to use .html(), you can do:
$('#item-of-interest').wrap('<div></div>').html()
It may be possible to use the jQuery.makeArray(obj) utility function:
var obj = $('<p />',{'class':'className'}).html('peekaboo');
var objArr = $.makeArray(obj);
var plainText = objArr[0];
If you want to stringify an HTML element in order to pass it somewhere and parse it back to an element try by creating a unique query for the element:
// 'e' is a circular object that can't be stringify
var e = document.getElementById('MyElement')
// now 'e_str' is a unique query for this element that can be stringify
var e_str = e.tagName
+ ( e.id != "" ? "#" + e.id : "")
+ ( e.className != "" ? "." + e.className.replace(' ','.') : "");
//now you can stringify your element to JSON string
var e_json = JSON.stringify({
'element': e_str
})
than
//parse it back to an object
var obj = JSON.parse( e_json )
//finally connect the 'obj.element' varible to it's element
obj.element = document.querySelector( obj.element )
//now the 'obj.element' is the actual element and you can click it for example:
obj.element.click();
new String(myobj)
If you want to serialize the whole object to string, use JSON.

How to the text within a pair of tags, like "my head" in "<h1>my head</h1>", by Javascript?

E.g.
<h1>my head</h1>
As I know, the below codes can print the h1,
var el = document.getElementsByTagName('h1')[0];
alert("tag : "+el.tagName);
But, how could I get the text between a pair of tags, i.e. my head ?
Use element.innerHTML
var el = document.getElementsByTagName('h1')[0];
alert("tag : "+el.innerHTML);
alert(el.firstChild.data);
This is the normal way with Dom
try by regx
var str = "<h1>my head</h1> ";
var result = str.match(/<h1>(.*?)<\/h1>/g).map(function(val){
return val.replace(/<\/?h1>/g,'');
});
by element.innerHTML
function getValue(){
var x=document.getElementsByTagName("h1");
alert(x.innerHTML);
}
Use el.firstChild.nodeValue
var el = document.getElementsByTagName('h1')[0];
alert("tag : "+el.firstChild.nodeValue);
Using innerHtml will also return the text value in this case since there are no child elements however if it had any they would also be returned as a string (e.g., my head) which doesn't sound like what you want.

Categories