.html() and .append() without jQuery - javascript

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>

Related

show all the values with .html [duplicate]

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.

Replace non-code text on webpage

I searched through a bunch of related questions that help with replacing site innerHTML using JavaScript, but most reply on targetting the ID or Class of the text. However, my can be either inside a span or td tag, possibly elsewhere. I finally was able to gather a few resources to make the following code work:
$("body").children().each(function() {
$(this).html($(this).html().replace(/\$/g,"%"));
});
The problem with the above code is that I randomly see some code artifacts or other issues on the loaded page. I think it has something to do with there being multiple "$" part of the website code and the above script is converting it to %, hence breaking things.using JavaScript or Jquery
Is there any way to modify the code (JavaScript/jQuery) so that it does not affect code elements and only replaces the visible text (i.e. >Here<)?
Thanks!
---Edit---
It looks like the reason I'm getting a conflict with some other code is that of this error "Uncaught TypeError: Cannot read property 'innerText' of undefined". So I'm guessing there are some elements that don't have innerText (even though they don't meet the regex criteria) and it breaks other inline script code.
Is there anything I can add or modify the code with to not try the .replace if it doesn't meet the regex expression or to not replace if it's undefined?
Wholesale regex modifications to the DOM are a little dangerous; it's best to limit your work to only the DOM nodes you're certain you need to check. In this case, you want text nodes only (the visible parts of the document.)
This answer gives a convenient way to select all text nodes contained within a given element. Then you can iterate through that list and replace nodes based on your regex, without having to worry about accidentally modifying the surrounding HTML tags or attributes:
var getTextNodesIn = function(el) {
return $(el)
.find(":not(iframe, script)") // skip <script> and <iframe> tags
.andSelf()
.contents()
.filter(function() {
return this.nodeType == 3; // text nodes only
}
);
};
getTextNodesIn($('#foo')).each(function() {
var txt = $(this).text().trim(); // trimming surrounding whitespace
txt = txt.replace(/^\$\d$/g,"%"); // your regex
$(this).replaceWith(txt);
})
console.log($('#foo').html()); // tags and attributes were not changed
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo"> Some sample data, including bits that a naive regex would trip up on:
foo<span data-attr="$1">bar<i>$1</i>$12</span><div>baz</div>
<p>$2</p>
$3
<div>bat</div>$0
<!-- $1 -->
<script>
// embedded script tag:
console.log("<b>$1</b>"); // won't be replaced
</script>
</div>
I did it solved it slightly differently and test each value against regex before attempting to replace it:
var regEx = new RegExp(/^\$\d$/);
var allElements = document.querySelectorAll("*");
for (var i = 0; i < allElements.length; i++){
var allElementsText = allElements[i].innerText;
var regExTest = regEx.test(allElementsText);
if (regExTest=== true) {
console.log(el[i]);
var newText = allElementsText.replace(regEx, '%');
allElements[i].innerText=newText;
}
}
Does anyone see any potential issues with this?
One issue I found is that it does not work if part of the page refreshes after the page has loaded. Is there any way to have it re-run the script when new content is generated on page?

how to remove bug character in html using jquery

I have a bug in my code and i try to remove it using jquery.
Some code:
<div id="content">
s
<div class="breadcrumb">
<h1>Test and etc</h1> etc etc....
I want to use jquery to remove the s (if exist...in some cases not)
I've tried
var cont = $('#content').html();
$('#content').html(cont.replace('/s\s(.*)/','$1'));
Seams that the code above is not working...some sugestions ?
Don't use a regex to remove a textnode by running a replace on the HTML, target the textnode directly
var content = document.getElementById('content'),
child = content.firstChild;
if (child.nodeType === 3) { // if textNode
content.removeChild(child);
}
FIDDLE
You do need to call the code when the DOM is ready. And remove the quotes.
$(document).ready(function(){
var cont = $('#content').html();
$('#content').html(cont.replace(/s\s(.*)/,'$1'));
});
Fiddle : http://jsfiddle.net/anj1x7xe/
I don't understand, why won't you remove it directly from the HTML source?
Is the code automatically generated (aka you didn't manually write that 's' there)? Because if it is, I strongly suggest you correct the bug itself. What you're trying to do is covering up a bug, not fixing it. It's good practice to get to the source of a bug and fix it.
Alas, if you really want to do this: You need to specify when your script is called. Most likely, you want it put into the $(document).ready() event.
$(document).ready(function(){
var cont = $('#content').html();
$('#content').html(cont.replace('/s\s(.*)/','$1'));
});

Replace html in userscript w/o breaking anything?

The below is in my userscript. It doesnt do the alert because when i replace the html i am clobbering it somehow.
How do i replace regular text in a div or span that is literally domain[dot]com so it will appear as domain.com? Well the below works but breaks code running after and other userscripts.
$(function() {
var html = $('body').html();
var res=html.replace(/\[dot\]/g, ".");
$('body').html(res);
//doesnt call, however html is replaced
alert('a');
});
Replace the text in the page instead of replacing in the entire HTML. If you get the entire HTML and put it back, that will make it reparse all the code and put it back as it was when initially loaded, whcih means that any events bound to any elements are gone.
Use a recursive function to find the text nodes in the document and do the replacing on the text in each node:
function replaceText(node, replacer) {
var n = node.childNodes;
for (var i = 0; i < n.length; i++) {
if (n[i].nodeType == 3) {
n[i].nodeValue = replacer(n[i].nodeValue);
} else {
replaceText(n[i], replacer);
}
}
}
$(function(){
replaceText(document.body, function(s){
return s.replace(/\[dot\]/g, '.');
});
});
Demo: http://jsfiddle.net/Guffa/ex83P/
As you see, there is no jQuery in the function, because jQuery only deals with elements, there are no methods to deal with text nodes.
Is this for a specific set of pages or do you plan on doing this across every page you encounter? If specific, try narrowing down your selectors significantly. This way you're not trying to process every span/div on the page (which is obv slow). Firebug should be able to help you.

How can I strip down JavaScript code while building HTML?

I am trying to parse some HTML to find images within it.
For example, I created a dynamic div and parsed the tags like this:
var tmpDiv = document.createElement("DIV");
tmpDiv.innerHTML = html;
The HTML should be script-less however there are exceptions, one code segment had the following code under an image tag:
<img src=\"path" onload=\"NcodeImageResizer.createOn(this);\" />
By creating a temp div the "onload" function invoked itself and it created a JavaScript error.
Is there anyway to tell the browser to ignore JavaScript code while building the HTML element?
Edit:
I forgot to mention that later on I'd like to display this HTML inside a div in my document so I'm looking for a way to ignore script and not use string manipulations.
Thanks!
One way of doing this is to loop through the children of the div and remove the event handlers you wish.
Consider the following:
We have a variable containing some HTML which in turn has an onload event handler attached inline:
var html = "<img src=\"http://www.puppiesden.com/pics/1/doberman-puppy5.jpg\"
alt=\"\" onload=\"alert('hello')\" />"
One we create a container to put this HTML into, we can loop through the children and remove the relevant event handlers:
var newDiv = document.createElement("div");
$(newDiv).html(html);
$(newDiv).children().each(function(){this.onload = null});
Here's a working example: http://jsfiddle.net/XWrP3/
UPDATE
The OP is asking about removing other events at the same time. As far as I know there's no way to remove all events in an automatic way however you can simply set each one to null as required:
$(newDiv).children().each(function(){
this.onload = null;
this.onchange = null;
this.onclick = null;
});
You can do it really easily with jquery like this:
EDIT:
html
<div id="content" style="display:none">
<!-- dynamic -->
</div>
js
$("#content").append(
$(html_string).find('img').each(function(){
$(this).removeAttr("onload");
console.log($(this).attr("src"));
})
);

Categories

Resources