How to render html partially inside div? - javascript

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>

Related

.innerHTML does not display the html code content I need

So I am trying to create text boxes dynamically using javascript, which is working fine, but when I try to use innerHTML to display the text boxes in nothing appears on my screen.
JavaScript Code:
var i = 1;
function instituteCreate(){
var y = document.createElement("INPUT");
y.setAttribute("type", "text");
y.setAttribute("Name", "institute_" + i);
document.getElementById('userdata').innerHTML = '<div class="row"><div class="col-md"><div
class="form-group"><div class="form-field">Institute';
document.getElementById('userdata').appendChild(y);
document.getElementById('userdata').innerHTML = '</div></div></div></div>';
i++;
}
I have the following in my html file:
<div id="userdata"></div>
And right before the closure I have the following which is calling the JS file:
<script src="js/addmore.js" type="text/javascript"></script>
When you use innerHTML with = you are completely reassigning everything inside of that element overwriting everything you had before.
You can either use += instead of = to not overwrite the value, and instead append.
Or create a template with backtick: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

selecting element from a html string inside variable

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

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

how to remove the lastchild element of dynamically generated DIV and return the html as string

How to remove the lastchild of the dynamically generated div and regenerate the html as string.
Sample HTML DIV
strHtmlString = "<div contenteditable='true' id='undefined'>Test1</div>
<div contenteditable='true' id='sentenceFreeTextField67' type='sentenceFreeTextField'>One</div>
<div id='multiselectAnchors' type='multi'>
<div id='options32' >Two</div>
<div contenteditable='true' id='sentenceFreeTextField68' type='sentenceFreeTextField'>One</div>
</div>
<div id='blank4' contenteditable='true' type='blankField'> </div>
<div id='Div1' type='multi'>
<div id='options33' >Three</div>
<div contenteditable='true' id='sentenceFreeTextField69' type='sentenceFreeTextField'>One</div>
</div>"
here is the code sample
if (($('<DIV/>').html(strSentence)[0].lastChild.lastChild.type === 'sentenceFreeTextField') && (!$.trim($('<DIV/>').html(strSentence)[0].lastChild.lastChild.innerText))) {
strHtmlString = $('<DIV/>').html(strSentence)[0].lastChild.lastChild.remove().html; (this remove().html doesn't work)
}
the need is to delete the lastchild of the div at runtime and convert back to string as it was earlier. I can do string manipulation however, might not the be the right way, please suggest
var el = $(strHtmlString);
// dont know what you meant by last child, so taking the id
el.children().find("#sentenceFreeTextField69").remove();
var str = el.wrap("<div/>").parent().html()
Generate a DIV dynamically:
$('body').append('<div>');
Access the DIV immediately after generation:
var $divElement = $('body').append('<div>').find('div');
Get the last child:
var $lastChildElement = $divElement.last();
Get the HTML of the last child (more specifically, the innerHTML):
var $lastChildHTML = $lastChildElement.html();
Do it all together then you turn around:
var $lastChildHTML = $('body').append('<div>').find('div').last().html();
That's what it's all about.
var last = $(element).children(':last-child');
var html = $(last).html();
$(last).remove();
var newHtml = $(element).html();
//incase you want the html with it's parent as well do this
var newHtml = $(element).parent().html();

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

Categories

Resources