How to get innerHTML from one specify child ELEMENT - javascript

All:
What I want to do is:
<div id="container">
<div class="unwanted"></div>
<div class="unwanted"></div>
<svg><rect></rect></svg>
<div class="unwanted"></div>
<div>
How can I get the innerHTML of #container for that svg, so what I get is:
"<svg><rect></rect></svg>"

What you want is the outerHTML of the svg Element but that is not really accessible in this way.
Here
outerHTML of an SVG element
is an idea of how to get the svg with content.

This will get you what you want in this case:
document.getElementById('container').getElementsByTagName('svg')[0].innerHTML;

jquery
var container = $("#container").html().find('svg');
// or
$("#container svg").html();
//return <rect></rect> you can use '<svg>'+container+'</svg>'
javascript
var container = document.getElementById('container');
var svg = container.getElementsByTagName('svg')[0].innerHTML;
//return <rect></rect> you can use '<svg>'+container+'</svg>'
or see #Duopixel's answer on Why .html() doesn't work with SVG selectors using jquery ?
var svg = document.getElementById('svg_root'); // or whatever you call it
var serializer = new XMLSerializer();
var str = serializer.serializeToString(svg);

Related

how to show html when using appendChild

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

How to clone an element using class name and append it to the body

I am trying to learn how to clone an element using classname and append it to the body.
here is what i have done but i am not getting any output. is there anything wrong ?
HTML:
<div class="check">hello</div>
CSS:
.check {
top: 100px;
}
JavaScript:
var elem = document.getElementsByClassName('.check');
var temp = elem[0].clonenode(true);
document.body.append(temp);
JSFiddle Link:
http://jsfiddle.net/hAw53/378/
if not JS, jquery solution is also welcomed.
You were almost there:
var elem = document.getElementsByClassName('check'); // remove the dot from the class name
var temp = elem[0].cloneNode(true); // capitalise "Node"
document.body.appendChild(temp); // change "append" to "appendChild"
<div class="check">hello</div>
You have 3 errors. Correct code:
var elem = document.getElementsByClassName('check'); // check, not .check
var temp = elem[0].cloneNode(true); // cloneNode, not clonenode
document.body.appendChild(temp); // appendChild, not append
Demo: http://jsfiddle.net/hAw53/379/
There are a few issues with your code.
getElementsByClassName() takes a class name (check), not a selector (.check)
cloneNode() is spelled with a capital N (not clonenode())
appendChild() is the name of the DOM method for appending a child (not append())
Correct version:
var elem = document.getElementsByClassName('check');
var temp = elem[0].cloneNode(true);
document.body.appendChild(temp);
You can do:
$('.check').clone().appendTo('body');
You're code had errors. First you used class selector and not the class name. Then you used an undefined property(properties are case sensitive) and you've to use appendChild instead of append which is a part of jQuery. You're too much confused with native javascript and jQuery.
in Jquery it's very simple, you just need to define inside what the new element apears.
var elem = $('.check');
elem.clone().prependTo( "body");

Get HTML fragment without text by jQuery

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

documentFragement

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>

How to get the HTML for a DOM element in javascript

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;

Categories