jQuery Object to HTML [duplicate] - javascript

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.

Related

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.

Filter in AngularJS - text in html tags

I'm not very good at filtering and wanted to write a custom filter based on the following:
I call a service that returns a JSON object with HTML String thats concatenated with another string - so the HTML is funky.
I want to get the text1 and text2 form the following returned HTML string:
<span><b>text1</b><b>text2</b>text3</span>
I have no control how the above is returned to me, but i just wanted to get the two values and concatenate them: text1text2
There is a builtin DOM parser - or you can find a parser in your environment. See on MDN parsing XML and Element. So you could do something like this:
var x = "<span><b>text1</b><b>text2</b>text3</span>";
var oDOM = new DOMParser().parseFromString(x, "text/xml");
var b = oDOM.documentElement.getElementsByTagName("b");
b.length // 2
b[1].innerHTML // text2
HTH
if you just need to strip the html tags, I think you can use the below code
var noHTML = OriginalString.replace(/(<([^>]+)>)/ig,"");
For a filter implementation
angular.module('myNoHtmlFilterApp', [])
.filter('noHtml', function() {
return function(input) {
input = input || '';
var out = input.replace(/(<([^>]+)>)/ig,"");
return out;
};
})
Based on DineSH's answer - I did something like this:
$scope.getTextFromHTML = function(html){
var oDOM = new DOMParser().parseFromString(html, "text/xml");
var b = oDOM.documentElement.getElementsByTagName("b");
return b[0].innerHTML+b[1].innerHTML;
};
I have to pre-define the html string since its not on the DOM yet, like so:
var html = "<span><b></b><b></b></span>";
I will probably add a for loop later in case there is a string I missed, but for now, this is perfect. Thank you for all of your help!

Find selector in array

I have to find and display a selector from HTML presented in array, this works for me using Jquery:
var a = '';
var b = Array.prototype.map.call($('p', a),
function(e) { return e.outerHTML; });
console.log(b)
However I don't want to use Jquery, Id rather use plain Javascript so I tried:
a.querySelectorAll('p')
Not working. Why is that and what else can I try?
You're using querySelectorAll as if it is available in the String.prototype object because the variable a is an empty string.
Try document.querySelectorAll('p');
I think what you want is this:
var b = Array.prototype.map.call(document.querySelectorAll("p"),
function(e) { return e.outerHTML; });
console.log(b);
This way your calling the query selector on the document rater than on an empty string(where the function won't exist).
Try this:
document.getElementsByTagName("p")
Which will return an array of all <p> tags

How do you extract an html snippet from a xml file using javascript?

I have javascript code that pulls information for a web page from an xml file and generates html and inserts the data. this works well.
getElementsByTagName("XmlNode")[0].childNodes[0].nodeValue;
when I change the data to an html hyperlink block nodeValue returns null.
<XmlNode><a href='URL'>URL text</a></XmlNode>
Is there some other property to use to return the contents of this XML node?
You are attempting to get the nodeValue of <a> rather than the text node inside of it. You can either add another .childNodes[0] to the chain to get to the text node or use .textContent in place of .nodeValue
You should use CDATA to hold markup inside your XML nodes.
<![CDATA[ html mark up ]]>
<XmlNode><![CDATA[<a href='URL'>URL text</a>]]></XmlNode>
I found out to do this:
var xmlSerializer = new XMLSerializer();
function innerXml(node)
{
return xmlSerializer.serializeToString(node)
}
Source: http://forums.asp.net/t/1341879.aspx/1
Edit:
After doing a little more research I actually used this:
function innerXml(node)
{
var innerXml = "";
var nodes = node.childNodes;
for(q=0;q<nodes.length;q++)
{
if (typeof window.XMLSerializer != "undefined")
innerXml += xmlSerializer.serializeToString(nodes[q]);
else if (typeof nodes[q].xml != "undefined")
innerXml += nodes[q].xml;
}
innerXml = innerXml.trim();
return innerXml;
}

Create string from HTMLDivElement

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

Categories