I'm creating some elements through this code in JavaScript:
var tdiv = document.createElement("div");
tdiv.setAttribute('id', 'titlediv');
var ddiv = document.createElement("div");
ddiv.setAttribute('id', 'datediv');
var cdiv = document.createElement("div");
cdiv.setAttribute('id', 'contentdiv');
Now I have to append some html text to cdiv. I tried to do cdiv.appendChild() but it displays an error since it is not a node. Tried doing var newsupdate_ = document.createTextNode(global[j].content) then appending it but it looks like this:
Can I do setAttribute to place the content inside the desired div?
appendChild() would not work in cdiv because there is no such method present in the element created by createElement().
createTextNode() creates a new Text node. It will not evaluate any HTML present in the parameter string.
Try innerHTML like the following way:
var cdiv = document.createElement("div");
cdiv.setAttribute('id', 'contentdiv');
cdiv.innerHTML = '<h1>Header 1</h1>';
document.getElementById('container').append(cdiv);
<div id="container"></div>
use innerHTML, example
document.getElementById("demo").innerHTML = "Paragraph changed!";
Related
I need to append some html to an existing element using pure javaScript:
function create(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
var target = document.querySelectorAll(".container-right");
var fragment = create(
'<div class="freetext"><p>Some text that should be appended...</p></div>'
);
document.body.insertBefore(fragment, document.body.childNodes[0]);
It's kind of working, but I have two questions:
How can I make sure that the html fragment is appended to the div with the class container-right and not just the body? Changing the last line to document.body.insertBefore(fragment, target); doesn't work.
How can I insert the html after the content in the target element - after the existing content - like jQuery's append()?
Any help is much appreciated.
JsFiddle here.
Well, I know this works:
let elem = document.querySelector ( 'css-selector (id or class)' )
That should give you your element. Then you do this:
elem.innerHTML = elem.innerHTML + myNewStuff;
That'll append your html to the innerHTML of the element. I tried it quickly, it works.
var target = document.querySelector(".container-right");
var p = document.createElement('p');
p.innerHTML = "Some text that should be appended...";
var div = document.createElement('div');
div.appendChild(p);
var fragment = document.createDocumentFragment();
fragment.appendChild(div);
target.appendChild(fragment);
JSFiddle
Try this:
var target = document.querySelector(".container-right");
target.innerHTML += '<div class="freetext"><p>Some text that should be appended...</p></div>';
Based on this answer to a similar question, I have found that insertAdjacentHTML is a good fit for this kind of problems.
I haven't tested it on a Node List, but with a single node it works perfectly.
insertAdjacentHTML has a great browser compatibility (back to IE4), plus it lets you decide where you want to insert the HTML (see here).
var target = document.querySelector(".container-right");
var newContent = '<div class="freetext"><p>Some text that should be appended...</p></div>';
target.insertAdjacentHTML('beforeend', newContent);
document.querySelectorAll('.container-right').forEach(elm=>{
elm.innerHTML += '<div class="freetext"><p>Some text that should be appended...</p></div>';
});
I have a HTML code with div container and another HTML element and text inside it
<div id="container"><i class="myico"></i> text</div>
I need to get only HTML element from the container without the text.
So i need to get only
<i class="myico"></i>
How can I get it using jQuery?
Simply to get the element use one of the following:
var element = $("#container > i");
var element = $("#container i");
var element = $("#container .myico");
var element = $("#container").find("i.myico");
To get the element out of the markup use detach():
var element = $("#container > i").detach();
Then to get an HTML code, you may use outerHTML property:
var html = element.get(0).outerHTML;
DEMO: http://jsfiddle.net/tLvdZ/
$('i') / $('.myico') / $('div i')... http://api.jquery.com/category/selectors/
var htmltag = $("#container").html();
htmltag = htmltag.replace($("#container").text(),"");
For reference you can use :- refer this
please take a look at the following code.
var oFra = document.createDocumentFragment();
var myDiv = document.createElement("div");
myDiv.id="myId";
oFra.appendChild(myDiv);
oFra.getElementById("myId");
In this case do i have ref to the div i just inserted inside documentFragement using the variable myDiv?
Lets say i move ahead and add this documentFragement to the actual DOM. Will I still be able to access the div with id="myId" using this "myDiv" variable???
If you try this, it works:
http://www.jsfiddle.net/dactivo/4BSaF/
The problem is that you cannot use "oFra" + getElementById directly, once you append the fragment, you can access the div "myId" in the DOM.
<div id="test"></div>
<script type="text/javascript">
var oFra = document.createDocumentFragment();
var myDiv = document.createElement("div");
myDiv.id="myId";
myDiv.innerHTML="hola";
oFra.appendChild(myDiv);
// oFra.getElementById("myId");
document.getElementById("test").appendChild(oFra);
alert(document.getElementById("myId").innerHTML);
</script>
I have some HTML loaded in WebView like this:
<html><head></head><body>before <myTag>Content</myTag> after</body></html>
I want to replace element myTag with custom text so it should look like:
<html><head></head><body>before ____MY_CUSTOM_TEXT___ after</body></html>
Also I can't change initial HTML.
How I can do this with JavaScript?
My not finished code:
var elements = document.getElementsByTagName( 'myTag' );
var firstElement = elements[0];
var parentElement = firstElement.parentNode;
var html = parentElement.innerHTML;
parentElement.innerHTML = html.replace(?????, '____MY_CUSTOM_TEXT___');
I don't know how to get string value of element to replace (?????).
Here you go:
var txt = document.createTextNode('____MY_CUSTOM_TEXT___');
parentElement.replaceChild(txt, firstElement);
Imagine I have the following HTML:
<div><span><b>This is in bold</b></span></div>
I want to get the HTML for the div, including the div itself. Element.innerHTML only returns:
<span>...</span>
Any ideas? Thanks
Use outerHTML:
var el = document.getElementById( 'foo' );
alert( el.outerHTML );
Expanding on jldupont's answer, you could create a wrapping element on the fly:
var target = document.getElementById('myElement');
var wrap = document.createElement('div');
wrap.appendChild(target.cloneNode(true));
alert(wrap.innerHTML);
I am cloning the element to avoid having to remove and reinsert the element in the actual document. This might be expensive if the element you wish to print has a very large tree below it, though.
First, put on element that wraps the div in question, put an id attribute on the element and then use getElementById on it: once you've got the lement, just do 'e.innerHTML` to retrieve the HTML.
<div><span><b>This is in bold</b></span></div>
=>
<div id="wrap"><div><span><b>This is in bold</b></span></div></div>
and then:
var e=document.getElementById("wrap");
var content=e.innerHTML;
Note that outerHTML is not cross-browser compatible.
old question but for newcomers that come around :
document.querySelector('div').outerHTML
You'll want something like this for it to be cross browser.
function OuterHTML(element) {
var container = document.createElement("div");
container.appendChild(element.cloneNode(true));
return container.innerHTML;
}
If you want a lighter footprint, but a longer script, get the elements innerHTML and only create and clone the empty parent-
function getHTML(who,lines){
if(!who || !who.tagName) return '';
var txt, ax, str, el= document.createElement('div');
el.appendChild(who.cloneNode(false));
txt= el.innerHTML;
ax= txt.indexOf('>')+1;
str= txt.substring(0, ax)+who.innerHTML+ txt.substring(ax);
el= null;
return lines? str.replace(/> *</g,'>\n<'): str;
//easier to read if elements are separated
}
var x = $('#container').get(0).outerHTML;
as outerHTML is IE only, use this function:
function getOuterHtml(node) {
var parent = node.parentNode;
var element = document.createElement(parent.tagName);
element.appendChild(node);
var html = element.innerHTML;
parent.appendChild(node);
return html;
}
creates a bogus empty element of the type parent and uses innerHTML on it and then reattaches the element back into the normal dom
define function outerHTML based on support for element.outerHTML:
var temp_container = document.createElement("div"); // empty div not added to DOM
if (temp_container.outerHTML){
var outerHTML = function(el){return el.outerHTML||el.nodeValue} // e.g. textnodes do not have outerHTML
} else { // when .outerHTML is not supported
var outerHTML = function(el){
var clone = el.cloneNode(true);
temp_container.appendChild(clone);
outerhtml = temp_container.innerHTML;
temp_container.removeChild(clone);
return outerhtml;
};
};
var el = document.getElementById('foo');
el.parentNode.innerHTML;