I'm looking for a method to insert a string, which contains HTML data, into a div element.
The string is loaded via XHR, and there is no way of knowing what elements and such are in it.
I've searched around for a bit, and found some things that might help, but wouldn't completely work for me. What I need is something similar to the update() function from the Prototype framework:
http://prototypejs.org/api/element/update
The platform I'm writing for does not allow frameworks to be used, or JQuery. I'm stuck with Javascript. Anyone have any ideas?
I can't use innerHTML, as it does not apply any updates or functions or basically anything that's supposed to occur on load
I have some onload events that need to occur, and as best I know, using innerHTML does not execute onload events. Am I incorrect?
EDIT 2 years later:
For anyone else reading, I had some serious misconceptions about the onload event. I expected that it was a valid event for any element, while it is only valid for the <body/> element. .innerHTML is the proper method to do what I was looking for, and any extra functionality for the elements added, needs to be done manually some other way.
HTMLElement innerHTML Property
The innerHTML property sets or returns the inner HTML of an element.
HTMLElementObject.innerHTML=text
Example: http://jsfiddle.net/xs4Yq/
You can do it in two ways:
var insertText = document.createTextNode(theText);
document.getElementById("#myid").appendChild(insertText);
or
object.innerHTML=text
I'm looking for a method to insert a string, which contains HTML data, into a div element.
What you want to use is the innerHTML property.
Example of use:
<script type="text/javascript">
function changeText(){
document.getElementById('boldStuff').innerHTML = '<p>Universe</p>';
}
</script>
<p>Hello <b id='boldStuff'>World</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
do you mean like this? : http://jsfiddle.net/FgwWk/1 or do you have things in the div already before adding more?
Plain JS.
Just use: element.insertAdjacentHTML(position, text);
position = "beforebegin" | "afterbegin" | "beforeend" | "afterend"
var text = '<a class="btn btn-blue btn-floating waves-effect">\n' +
'<i class="fas fa-user"><span class="badge badge-danger"></span></i>\n' +
'</a>';
var inputPlace = document.getElementById("input-pace");
inputPlace.insertAdjacentHTML("beforeend", text);
Related
Lets say I have an empty div:
<div id='myDiv'></div>
Is this:
$('#myDiv').html("<div id='mySecondDiv'></div>");
The same as:
var mySecondDiv=$("<div id='mySecondDiv'></div>");
$('#myDiv').append(mySecondDiv);
Whenever you pass a string of HTML to any of jQuery's methods, this is what happens:
A temporary element is created, let's call it x. x's innerHTML is set to the string of HTML that you've passed. Then jQuery will transfer each of the produced nodes (that is, x's childNodes) over to a newly created document fragment, which it will then cache for next time. It will then return the fragment's childNodes as a fresh DOM collection.
Note that it's actually a lot more complicated than that, as jQuery does a bunch of cross-browser checks and various other optimisations. E.g. if you pass just <div></div> to jQuery(), jQuery will take a shortcut and simply do document.createElement('div').
EDIT: To see the sheer quantity of checks that jQuery performs, have a look here, here and here.
innerHTML is generally the faster approach, although don't let that govern what you do all the time. jQuery's approach isn't quite as simple as element.innerHTML = ... -- as I mentioned, there are a bunch of checks and optimisations occurring.
The correct technique depends heavily on the situation. If you want to create a large number of identical elements, then the last thing you want to do is create a massive loop, creating a new jQuery object on every iteration. E.g. the quickest way to create 100 divs with jQuery:
jQuery(Array(101).join('<div></div>'));
There are also issues of readability and maintenance to take into account.
This:
$('<div id="' + someID + '" class="foobar">' + content + '</div>');
... is a lot harder to maintain than this:
$('<div/>', {
id: someID,
className: 'foobar',
html: content
});
They are not the same. The first one replaces the HTML without creating another jQuery object first. The second creates an additional jQuery wrapper for the second div, then appends it to the first.
One jQuery Wrapper (per example):
$("#myDiv").html('<div id="mySecondDiv"></div>');
$("#myDiv").append('<div id="mySecondDiv"></div>');
Two jQuery Wrappers (per example):
var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').html(mySecondDiv);
var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').append(mySecondDiv);
You have a few different use cases going on. If you want to replace the content, .html is a great call since its the equivalent of innerHTML = "...". However, if you just want to append content, the extra $() wrapper set is unneeded.
Only use two wrappers if you need to manipulate the added div later on. Even in that case, you still might only need to use one:
var mySecondDiv = $("<div id='mySecondDiv'></div>").appendTo("#myDiv");
// other code here
mySecondDiv.hide();
if by .add you mean .append, then the result is the same if #myDiv is empty.
is the performance the same? dont know.
.html(x) ends up doing the same thing as .empty().append(x)
Well, .html() uses .innerHTML which is faster than DOM creation.
.html() will replace everything.
.append() will just append at the end.
You can get the second method to achieve the same effect by:
var mySecondDiv = $('<div></div>');
$(mySecondDiv).find('div').attr('id', 'mySecondDiv');
$('#myDiv').append(mySecondDiv);
Luca mentioned that html() just inserts hte HTML which results in faster performance.
In some occassions though, you would opt for the second option, consider:
// Clumsy string concat, error prone
$('#myDiv').html("<div style='width:'" + myWidth + "'px'>Lorem ipsum</div>");
// Isn't this a lot cleaner? (though longer)
var newDiv = $('<div></div>');
$(newDiv).find('div').css('width', myWidth);
$('#myDiv').append(newDiv);
Other than the given answers, in the case that you have something like this:
<div id="test">
<input type="file" name="file0" onchange="changed()">
</div>
<script type="text/javascript">
var isAllowed = true;
function changed()
{
if (isAllowed)
{
var tmpHTML = $('#test').html();
tmpHTML += "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
$('#test').html(tmpHTML);
isAllowed = false;
}
}
</script>
meaning that you want to automatically add one more file upload if any files were uploaded, the mentioned code will not work, because after the file is uploaded, the first file-upload element will be recreated and therefore the uploaded file will be wiped from it. You should use .append() instead:
function changed()
{
if (isAllowed)
{
var tmpHTML = "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
$('#test').append(tmpHTML);
isAllowed = false;
}
}
This has happened to me . Jquery version : 3.3.
If you are looping through a list of objects, and want to add each object as a child of some parent dom element, then .html and .append will behave very different. .html will end up adding only the last object to the parent element, whereas .append will add all the list objects as children of the parent element.
I am a beginner in HTML and I want to create a region on a HTML page where the values keep on changing. (For example, if the region showed "56" (integer) before, after pressing of some specific button on the page by the user, the value may change, say "60" (integer) ).
Please note that this integer is to be supplied by external JavaScript.
Efforts I have put:
I have discovered one way of doing this by using the <canvas> tag, defining a region, and then writing on the region. I learnt how to write text on canvas from http://diveintohtml5.info/canvas.html#text
To write again, clear the canvas, by using canvas.width=canvas.width and then write the text again.
My question is, Is there any other (easier) method of doing this apart from the one being mentioned here?
Thank You.
You can normally do it with a div. Here I use the button click function. You can do it with your action. I have use jquery for doing this.
$('.click').click(function() {
var tempText = your_random_value;
// replace the contents of the div with the above text
$('#content-container').html(tempText);
});
You can edit the DOM (Document Object Model) directly with JavaScript (without jQuery).
JavaScript:
var number = 1;
function IncrementNumber() {
document.getElementById('num').innerText = number;
number++;
}
HTML:
<span id="num">0</span>
<input type='button' onclick='IncrementNumber()' value='+'/>
Here is a jsfiddle with an example http://jsfiddle.net/G638z/
I want to overwrite some text defined by class=cc-product-infolink and it is defined by the CMS, so i have to change the text in this class via JS. It is my first time to use it, so i have wrote a little script, but it doesn't work. Why?
I would like to change the text "inkl. MwSt, zzgl. Versandkosten " in "inkl. MwSt, Versandkosten gemäß Angaben". And the JS-Code must be work in the head, because there is no possibility to put it into the body.
Here is my HTML Code:
<div class="cc-product-infolink">
<a class="cc-no-clickable-arrow" href="/j/shop/info/m/me6f40c3b0bd58b35" rel="nofollow">inkl. MwSt, zzgl. Versandkosten</a>
</div>
My JS-Code
<script type="text/javascript">
//<![CDATA[
var versand = document.getElementsByClassName('cc-product-infolink')[0];
versand.getElementsByTagName('a')[0].textContent += ' gemäß Angaben';
//]]>
</script>
and it should work here: http://www.wonnemond.de/taschen/karl/#cc-m-product-8254989095
Maybe somebody can help me.
var versand = document.getElementsByClassName('cc-product-infolink')[0];
versand.getElementsByTagName('a')[0].textContent += ' gemäß Angaben';
Some notes:
id and class are not the same. As the name implies, getElementById retrieves elements by their id attribute. Your element only has class, so getElementsByClassName is what you need. I guess you cannot change the HTML.
textContent is used to set/get
the text content of a DOM element. Old IEs (IE8 and older) use
innerText instead.
firstChild does not work because the link is not the first child of that div. There is a text node containing a newline and some indentation before the link. Using getElementsByTagName you can solve this problem though.
And a jsFiddle Demo.
Can anyone tell me how can I use these two functions without using jQuery?
I am using a pre coded application that I cannot use jQuery in, and I need to take HTML from one div, and move it to another using JS.
You can replace
var content = $("#id").html();
with
var content = document.getElementById("id").innerHTML;
and
$("#id").append(element);
with
document.getElementById("id").appendChild(element);
.html(new_html) can be replaced by .innerHTML=new_html
.html() can be replaced by .innerHTML
.append() method has 3 modes:
Appending a jQuery element, which is irrelevant here.
Appending/Moving a dom element.
.append(elem) can be replaced by .appendChild(elem)
Appending an HTML code.
.append(new_html) can be replaced by .innerHTML+=new_html
Examples
var new_html = '<span class="caps">Moshi</span>';
var new_elem = document.createElement('div');
// .html(new_html)
new_elem.innerHTML = new_html;
// .append(html)
new_elem.innerHTML += ' ' + new_html;
// .append(element)
document.querySelector('body').appendChild(new_elem);
Notes
You cannot append <script> tags using innerHTML. You'll have to use appendChild.
If your page is strict xhtml, appending a non strict xhtml will trigger a script error that will break the code. In that case you would want to wrap it with try.
jQuery offers several other, less straightforward shortcuts such as prependTo/appendTo after/before and more.
To copy HTML from one div to another, just use the DOM.
function copyHtml(source, destination) {
var clone = source.ownerDocument === destination.ownerDocument
? source.cloneNode(true)
: destination.ownerDocument.importNode(source, true);
while (clone.firstChild) {
destination.appendChild(clone.firstChild);
}
}
For most apps, inSameDocument is always going to be true, so you can probably elide all the parts that function when it is false. If your app has multiple frames in the same domain interacting via JavaScript, you might want to keep it in.
If you want to replace HTML, you can do it by emptying the target and then copying into it:
function replaceHtml(source, destination) {
while (destination.firstChild) {
destination.removeChild(destination.firstChild);
}
copyHtml(source, destination);
}
Few years late to the party but anyway, here's a solution:
document.getElementById('your-element').innerHTML += "your appended text";
This works just fine for appending html to a dom element.
.html() and .append() are jQuery functions, so without using jQuery you'll probably want to look at document.getElementById("yourDiv").innerHTML
Javascript InnerHTML
Code:
<div id="from">sample text</div>
<div id="to"></div>
<script type="text/javascript">
var fromContent = document.getElementById("from").innerHTML;
document.getElementById("to").innerHTML = fromContent;
</script>
What?! I know, what a bad idea.
Firstly I have no control over the html that was output, its from a vendor and it is produced via their crazy system that our company has an agreement with. (let's not talk about the situation, I know it's not optimal)
In the html I have:
<a id="notify" onclick="location.href='index.php?foo=bar';return false;" href="javascript:;">Notify!</a>
In my JS If I do:
console.log($("#notify").attr("onclick"))
I recive:
onclick(event)
Which makes sense, but I need to change the onclick's attribute, so it reads to something like:
onclick="location.href='index.php?foo=bar&zoobazz=moo';return false;"
better yet, if I could remove the onclick and replace the href attributes value with location.href.
This will give you the function in a string
$("#notify").attr("onclick").toString()
Grep the URL after that
If I understand your question correctly, you want to actually see what the onclick event is doing and append to it, not just replace it. I tried this in chrome and it works, but it's pretty much a hack. Basically, when you get a reference to the "click" or "onclick" event function (using either jQuery or pure JS), then you can to a ".toString()" on it to convert the function into a string. Then you just strip off the "function" definition using some trickery and you're left with what you need - "location.href='.......".
Then just append your additional parameters. Hopefully this leads you in the right direction.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var $target = $("#notify");
var funcBody = $target.attr("onclick").toString().split("\n")[1].split(";")[0];
$target.attr("onclick","").attr("href", funcBody);
});
</script>
</head>
<body>
<a id="notify" onclick="location.href='index.php?foo=bar';return false;" href="javascript:;">Notify!</a>
</body>
</html>
document.getElementById('notify').onclick = function() {location.href='index.php?foo=bar&zoobazz=moo';return false;};
Does
$("#notify").click(function() { $("#notify").attr("onclick", "location.href='index.php?foo=bar&zoobazz=moo';"); return false;})
not do what you need it to do?
You can set onclick by using $("#foo").click = '';
You can change href by changing the attribute, using .attr(key, value);
http://docs.jquery.com/Attributes, and http://docs.jquery.com/Tutorials:Edit_in_Place_with_Ajax
so
$('#foo').click = '';
$('#foo').attr('href', 'whateveryousetitto');
I may be reading too much into the question, but I think OP is asking how to get the event code so that it can be manipulated, not just replaced. When specifying "index.php?foo=bar", I don't think the value of bar is known. If this was a known value, then why read the onclick value at all?
alert($('#notify').click);
?