how to put element into <div> by innerHTML or other ways? - javascript

This is my code:
var turn = 1;
var boardPiece;
var piece = [];
function init() {
boardPiece = document.getElementById("pages");
while (boardPiece.firstElementChild) {
if (typeof boardPiece.firstElementChild.id != 'undefined') {
piece.push(boardPiece.firstElementChild);
}
boardPiece.removeChild(boardPiece.firstElementChild);
}
document.getElementById("content").innerHTML = piece[0]; //My problem is here
}
init();
<div id="content">
</div>
<div id="pages">
<div id="page1" class="page">
...
</div>
<div id="page2" class="page">
...
</div>
</div>
The result is a text
[object HTMLDivElement]
not an element.
What's wrong with my .innerHTML? And what is typeof piece[0]? Is it text?

You need to replace your:
document.getElementById("content").innerHTML = piece[0];
with:
document.getElementById("content").innerHTML = piece[0].innerHTML;
What you are trying to do atm is to insert element (which is an object) as a plain text.

You need to use the .innerHTML along with your piece[0] variable like,
document.getElementById("content").innerHTML = piece[0].innerHTML;
Working Fiddle: https://jsfiddle.net/gs0yy50t/
Hope this helps!

The issue is that the type of piece[0] is not a string, but a HTML element. For that reason, in order to assign it to the content's innerHTML (which is a string), JavaScript is implicitly calling the piece[0].toString() method.
When calling the toString() method in HTML nodes (like most non-string objects in JavaScript), it returns a string representing the type of the object.
If you need to add the element piece[0] as child of content, then you should do:
document.getElementById("content").innerHTML = piece[0].outerHTML;
However, if what you need is to copy the content of one element into another, you should use the property innerHTML instead:
document.getElementById("content").innerHTML = piece[0].innerHTML;
Basically, both properties are strings with the HTML code of the element but outerHTML includes the element itself in the root.

Related

Create H1 element in div jQuery

I want to a <h1></h1> element in a div element in HTML with jQuery. How do I do this?
function show() {
let text = "greetings"
let divElem = document.getElementById("hello");
divElem.innerHTML = '<h1>${text}</h1>'
}
<div id="hello"></div>
<button onclick="show()">show</button>
Basically, I want to make an h1 element in the div element which displays the string contained in the text variable, "greetings" how do I do this?
Do you need to ` instead of ' ?!
Also can read about it in this link : Template literals (Template strings).
function show() {
let text = "greetings"
let divElem = document.getElementById("hello");
divElem.innerHTML = `<h1>${text}</h1>`
}
<div id="hello"></div>
<button onclick="show()">show</button>
You can use the Jquery .html() method.
Also, you have to use backticks instead of quotes. (`) in order to use templating inside a "string". This is called Template literals. You can read more about them here
function show() {
let text = "greetings"
$( "#hello" ).html( `<h1>${text}</h1>` );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="hello"></div>
<button onclick="show()">show</button>

Getting the actual name of the class, and not the element within it?

To get elements using a class name, document.getElementsByClassName() can be used.
But is there a function in JavaScript to get the actual name of the class itself?
Example:
var classElement = document.getElementsByClassName('myClass');
var printResult = document.getElementById('result');
printResult.innerHTML = classElement[0].innerHTML;
<div class="myClass">Hello</div>
<div id="result"></div>
printResult will just print out "Hello". What if I want the result to print out the string "myClass" which is the actual class name?
I tried classElement[0].className.innerHTML but it returns undefined.
className is a property of the dom node containing the classes of the element.
You don't need to add innerHTML, which is another property of the dom node and returns/sets the html content of the corresponding element.
var classElement = document.getElementsByClassName('myClass');
var printResult = document.getElementById('result');
printResult.innerHTML = classElement[0].className;
<div class="myClass">Hello</div>
<div id="result"></div>

Javascript for fetching the contents of an web page?

I want to fetch the value of class .cell-hover through javascript and it should print the value which is present in double quotes. So far I tried:
var phonenumbers = document.getElementsByClassName('cell-hover');
document.write(phonenumbers);
but its printing [object HTMLCollection], and I want to print the exact value.
Attached Snapshot:
document.getElementsByClassName('cell-hover'); will return an array of elements with class name cell-hover.Loop through that and print the result.For the content inside that class use innerHTML. The innerHTML will return DOM content as a String
You can also use node.textContent; if you know that your div contains only text
Here in the snippet i have printed the content of the first element with class name cell-hover
var phonenumbers = document.getElementsByClassName('cell-hover');
document.write( phonenumbers[0].innerHTML);
<div class="cell-hover">
2637145689
</div>
var phonenumbers = document.getElementsByClassName('cell-hover');
for(var i=0; i < phonenumbers.length ; i++){
document.write( phonenumbers[0].textContent );
}
<div class="cell-hover">
2637145689
</div>
One liner:
document.write(document.querySelector('.cell-hover').innerHTML);
document.write(document.querySelector('.cell-hover').innerText);

how to get value of an element using getElementById and getElementsByTagName together

I am trying to prettyprint the value of <pre> element for which I will be getting either xml or JSON as string, so I am trying to get the value first and then test if it is xml or json and call respective prettyprint methods here is my code ...
function showData(attName) {
var attData = document.getElementById(attName).getElementsByTagName('pre')[0];
alert(attData);
// once I get the value would like to test whether it is xml or json
//if (attData contains xml test condition )
prettyPrint.xml(attData);
else prettyPrint.json(attData);
document.getElementById('Details').style.display='none';
document.getElementById(attName).style.display='block';
}
So the showData will be called whenever I click on View link in the below code ..
<div id="Details" class="body">
View
</div>
<div id="${attachmentName}" style="display:none; margin-left:60px; margin-top:5px;position:absolute;background-color:#F8F8F8;padding:10px" >
<h1>${attachmentName}:${attachmentId}</h1>
<h5 style="color: #FF0066;"> [X Close] </h5> <br/>
<pre class="prettyprint">${attachmentData}</pre>
</div>
In alert I am getting [object HTMLPreElement] but not sure how to make it to string, so I have also tried ...
var objectHTMLCollection = document.getElementById(attName).getElementsByTagName('pre')[0],
string = [].map.call( objectHTMLCollection, function(node){
return node.textContent || node.innerText || "";
}).join("");
alert (objectHTMLCollection);
But still getting as HTMLPreElement...
I have tried the JQuery jQuery('#'+attName).find('.prettyprint').data(); but got the result as [object Object] .
I don't have much exposure in the JavaScript,may be I am not doing it in right way. It would be great if anyone can help on this.
Add .innerHTML - should work, get rid of the complicated mapping functions that are meant to work with multiple <pre> tags at once.
var attData = document.getElementById(attName).getElementsByTagName('pre')[0].innerHTML;
alert(attData);
If you're using jQuery:
var text = $("#" + attName + " pre:first").text();
That gets you the text content of the element.
Your last js snippet is close, but you're calling map on a non-array object, and passing the wrong var to alert(). To find all 'pre' elements:
var objectHTMLCollection = document.getElementsByTagName('pre');
var str = [].map.call( objectHTMLCollection, function(node){
return node.textContent || node.innerText || "";
}).join("");
alert (str);
If you are actually only looking for one 'pre' element:
var htmlObject = document.getElementById(attName);
var str = htmlObject.textContent || htmlObject.innerText || "";
alert (str);
Remember, an element's id is unique, so there's no point in querying by id, and tag name.

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