Is there a way to convert HTML like:
<div>
<span></span>
</div>
or any other HTML string into DOM element? (So that I could use appendChild()). I know that I can do .innerHTML and .innerText, but that is not what I want -- I literally want to be capable of converting a dynamic HTML string into a DOM element so that I could pass it in a .appendChild().
Update: There seems to be confusion. I have the HTML contents in a string, as a value of a variable in JavaScript. There is no HTML content in the document.
You can use a DOMParser, like so:
var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";
var doc = new DOMParser().parseFromString(xmlString, "text/xml");
console.log(doc.firstChild.innerHTML); // => <a href="#">Link...
console.log(doc.firstChild.firstChild.innerHTML); // => Link
You typically create a temporary parent element to which you can write the innerHTML, then extract the contents:
var wrapper= document.createElement('div');
wrapper.innerHTML= '<div><span></span></div>';
var div= wrapper.firstChild;
If the element whose outer-HTML you've got is a simple <div> as here, this is easy. If it might be something else that can't go just anywhere, you might have more problems. For example if it were a <li>, you'd have to have the parent wrapper be a <ul>.
But IE can't write innerHTML on elements like <tr> so if you had a <td> you'd have to wrap the whole HTML string in <table><tbody><tr>...</tr></tbody></table>, write that to innerHTML and extricate the actual <td> you wanted from a couple of levels down.
Why not use insertAdjacentHTML
for example:
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here
Check out John Resig's pure JavaScript HTML parser.
EDIT: if you want the browser to parse the HTML for you, innerHTML is exactly what you want. From this SO question:
var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;
Okay, I realized the answer myself, after I had to think about other people's answers. :P
var htmlContent = ... // a response via AJAX containing HTML
var e = document.createElement('div');
e.setAttribute('style', 'display: none;');
e.innerHTML = htmlContent;
document.body.appendChild(e);
var htmlConvertedIntoDom = e.lastChild.childNodes; // the HTML converted into a DOM element :), now let's remove the
document.body.removeChild(e);
Here is a little code that is useful.
var uiHelper = function () {
var htmls = {};
var getHTML = function (url) {
/// <summary>Returns HTML in a string format</summary>
/// <param name="url" type="string">The url to the file with the HTML</param>
if (!htmls[url])
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, false);
xmlhttp.send();
htmls[url] = xmlhttp.responseText;
};
return htmls[url];
};
return {
getHTML: getHTML
};
}();
--Convert the HTML string into a DOM Element
String.prototype.toDomElement = function () {
var wrapper = document.createElement('div');
wrapper.innerHTML = this;
var df= document.createDocumentFragment();
return df.addChilds(wrapper.children);
};
--prototype helper
HTMLElement.prototype.addChilds = function (newChilds) {
/// <summary>Add an array of child elements</summary>
/// <param name="newChilds" type="Array">Array of HTMLElements to add to this HTMLElement</param>
/// <returns type="this" />
for (var i = 0; i < newChilds.length; i += 1) { this.appendChild(newChilds[i]); };
return this;
};
--Usage
thatHTML = uiHelper.getHTML('/Scripts/elevation/ui/add/html/add.txt').toDomElement();
Just give an id to the element and process it normally eg:
<div id="dv">
<span></span>
</div>
Now you can do like:
var div = document.getElementById('dv');
div.appendChild(......);
Or with jQuery:
$('#dv').get(0).appendChild(........);
You can do it like this:
String.prototype.toDOM=function(){
var d=document
,i
,a=d.createElement("div")
,b=d.createDocumentFragment();
a.innerHTML=this;
while(i=a.firstChild)b.appendChild(i);
return b;
};
var foo="<img src='//placekitten.com/100/100'>foo<i>bar</i>".toDOM();
document.body.appendChild(foo);
Alternatively, you can also wrap you html while it was getting converted to a string using,
JSON.stringify()
and later when you want to unwrap html from a html string, use
JSON.parse()
Related
I have html string data inside variable like this
var htmlstring = "<div><div class='testdiv'>924422</div></div>"
What I am expecting is to fetch content of div having class.In this example .testdiv data.
How can I achieve?.
I know one approach: Append this html string to html page and then access.But I dont want to do it as I am using ajax and server returning kind of html string.Now I want to fetch data inside specific div.
So is there any alternative way to do?
First you don't use . in class name in html. And to fetch the content of that div in html string, you could use jquery find function.
var htmlstring = "<div><div class='testdiv'>924422</div></div>"
alert($(htmlstring).find('.testdiv').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here's a way you can achieve it without jQuery.
var htmlstring = "<div><div class='testdiv'>924422</div></div>";
function getTestDiv(htmlString) {
var textVal = null;
var div = document.createElement('div');
div.innerHTML = htmlString;
var elements = div.childNodes;
if (elements.item(0).childNodes.item(0).className === 'testdiv') {
textVal = elements.item(0).childNodes.item(0).innerHTML;
}
return textVal;
}
console.log(getTestDiv(htmlstring));
You can do this by :
console.log($(htmlstring).find("div.testdiv").text());
I'm making a messenger and my messages don't ignore HTML tags because I simply past a text from input in innerHTML of message. My code:
function Message(sender) {
...
this["text"] = "";
...
this.addText = function (text) {
this["text"] = text;
};
...
};
And here I display it:
...
var chatMessageText = document.createElement("p");
chatMessageText.innerHTML = message["text"];
...
What can I do for ignoring HTML tags in message["text"]?
Update Node#innerText property(or Node#textContent property).
chatMessageText.innerText = message["text"];
Check the difference of both here : innerText vs textContent
Refer : Difference between text content vs inner text
You can't. The point of innerHTML is that you give it HTML and it interprets it as HTML.
You could escape all the special characters, but the easier solution is to not use innerHTML.
var chatMessagePara = document.createElement("p");
var chatMessageText = document.createTextNode(message["text"]);
chatMessagePara.appendChild(chatMessageText)
I have this text
var test = "<span data-toggle="tooltip" title="2Test">1TEST</span>";
I don't rely not sure what I am doing and could need some help. This is what I tried:
test = test.replace(/<span data-toggle="tooltip" title="|">[^>]*>/gi, "");
The test variable should only return the value inside of "title".
I agree with #Biffen you shouldn't really parse HTML with regex! But if you must do it, try this...
var test = "<span data-toggle='tooltip' title='2Test'>1TEST</span>";
var result = test.match(/title='([^']+)'/)[1];
console.log(result); //2Test
You don't need to parse HTML to get the title attribute, instead you can access title attribute from HTML DOM.
Create a temporary container with createElement, then set inner html with your html string, lastly traverse to first child which is the span and get the title attribute that you want.
Example:
var test = "<span data-toggle='tooltip' title='2Test'>1TEST</span>";
var el = document.createElement('div');
el.innerHTML = test;
var title = el.firstChild.getAttribute('title')
console.log(title) //2Test
In my JavaScript code I have a string that contains something like:
var html = "<div class='outer'><div id='inner'>lots more html in here</div></div>";
I need to convert this to the string
var html = "<div id='inner'>lots more html in here</div>";
I'm already using using jQuery in my project, so I can use this to do it if necessary.
Why all these needlessly complex answers?
//get a reference to the outer div
var outerDiv = document.getElementById('outerDivId');//or $('#outerDivId')[0];
outerDiv.outerHTML = outerDiv.innerHTML;
And that's it. Just set the outerHTML to the inner, and the element is no more.
Since I had overlooked that you're dealing with an HTML string, it needs to be parsed, first:
var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;
var outerDiv = tempDiv.getElementsByTagName('div')[0];//will be the outer div
outerDiv.outerHTML = outerDiv.innerHTML;
And you're done.
Try:
var html = "<div class='outer'>"
+ "<div id='inner'>lots more html in here</div></div>";
html = $(html).html();
alert(html);
http://jsfiddle.net/TTEwm/
Try .unwrap() -
$("#inner").unwrap();
If html string always look like in your example you can use this simple code
var html = "<div class='outer'><div class='inner'>lots more html in here</div></div>";
html = html.slice(19,-6)
You can do something like this:
var html = "<div id='inner'>" + html.split("<div id='inner'>")[1].split("</div>")[0] + "</div>";
But you may want to add more protection for variations (in case you have the bad habit of not writing code using the same conventions), e.g "inner" or <DIV>
Demo
With below code, I am trying to match a text in a web page to get rid of html tags in a page.
var body = $(body);
var str = "Search me in a Web page";
body.find('*').filter(function()
{
$(this).text().indexOf(str) > -1;
}).addClass('FoundIn');
$('.FoundIn').text() = $('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>");
But it does not seems to work.. Please have a look at this and let me know where the problem is...
here is the fiddle
I have tried the below code instead..
function searchText()
{
var rep = body.text();
alert(rep);
var temp = "<font style='color:blue; background-color:yellow;'>";
temp = temp + str;
temp = temp + "</font>";
var rep1 = rep.replace(str,temp);
body.html(rep1);
}
But that is totally removing html tags from body...
change last line of your code to below one...you are using assignment operator which works with variables not with jquery object ..So you need to pass the replaced html to text method.
$('.FoundIn').text($('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>"))
try this.
$('*:contains("Search me in a Web page")').text("<span class='redT'>Search me in a Web page</span>");