selecting element from a html string inside variable - javascript

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());

Related

How to render html partially inside div?

I have a div and I want to set some text inside this div. Problem is my text contains HTML elements and I don't want all these elements to be rendered. I mean some elements must rendered as HTML.
Is there any way to create a div content like this?
I want to create a div element like below;
<div id="bodyContent">
</div>
Setting with html method is not working.
var myHTMLContentPart1 = "<HTML><BODY>";
var myHTMLContentPart2 = "<span>hello</span>";
var myHTMLContentPart3 = "</BODY></HTML>";
$("#bodyContent").html(?);
EDIT:
I recommend you to use regex to remove html or body tags, also you can add any tag that you want to remove like this <\/?tagname>
html = '<html><body><span>Some Text</span></body></html>';
clean = html.replace(/<\/?html>|<\/?body>/g, '');
console.log(clean);
// For your code
var myHTMLContentPart1 = "<HTML><BODY>";
var myHTMLContentPart2 = "<span>hello</span>";
var myHTMLContentPart3 = "</BODY></HTML>";
var html = myHTMLContentPart1 + myHTMLContentPart2 + myHTMLContentPart3;
clean = html.replace(/<\/?html>|<\/?body>/g, '');
$("#bodyContent").html(clean);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bodyContent">
</div>

get html from a variable by id

i have a variable name value in my javascript code that contain html data.i want to get the data inside form specific id that is inside #myDiv
var value="<div >
<p class="">Hi cname#gmail.com</p>
<br/>
<br/>
<br/>
<div id="myDiv">
sgdhsagdhagh
dhsajdgasj
cjzjcg
</div>
</div>"
Thanks
You should create a DOM element, then traverse up to it and get html() or .text()
var value = '<div >\
<p class="">Hi cname#gmail.com</p>\
<br/>\
<br/>\
<div id="myDiv">\
sgdhsagdhagh\
dhsajdgasj\
cjzjcg\
</div>\
</div>';
alert($(value).find('#myDiv').html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you need to get parent element, then use
alert($('<div />', {html: value}).find('#myDiv').html())
How about you do like this?
var variable = "stuff n things";
document.getElementById( 'myDiv' ).innerHTML = variable;
Thats the native way :)
EDIT:
if you want to get the data you just do like this:
var variable = document.getElementById( 'myDiv' ).innerHTML;
That will give you the markup of whats inside the div.
Or use document.querySelector("#myDiv") to get the first match on the selector.querySelectorAll returns array.
You can use the HTML of the value variable to create an jQuery object. From this object you can search for the element with the id, and get its HTML content:
var html = $(value).find('#myDiv').html();
console.log(html); //sgdhsagdhaghdhsajdgasjcjzjcg
Or a pure javascript implementation:
var el = document.createElement('div');
el.innerHTML = value;
var html = el.getElementById('myDiv').innerHTML;
console.log(html); //sgdhsagdhaghdhsajdgasjcjzjcg
Using plain Javascriptuse:
document.getElementById("myDiv").innerHTML;
Using jQuery:
$("#myDiv").html();
There are Two ways- Angular way-
var elem = angular.element(value);
var innerDive=elem[0].getElementById('myDiv');
var text= angular.element(innerDive[0]).innerText;
Jquery-
var text= $(value).find('#myDiv').text();

remove outer div

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

Match a String in a Webpage along with HTML tags

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>");

Converting HTML string into DOM elements?

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()

Categories

Resources