How can I strip down JavaScript code while building HTML? - javascript

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"));
})
);

Related

In php script code document.createElement('p').textContent is not null or something like that, but it won't display the created element. Why?

I'm new in php programming. I'm in a very interesting moment.
let str = 'anytext';
line = document.createElement('p');
line.textContent = str;
alert('line = ' + line.textContent);
I tried to use and .textContent and .innerHTML and .innerText. Nothing. It refuses to display anything.
The alert shows that the value successfully assigned. No errors, but there is nothing displayed on
the screen of the browser. I mean, no paragraph element created visually.
I use javascript not in html document. I use it in php file.
The page has a table, which I created programmatically with php.
I thought I can solve this problem by sending the
$html = new DOMDocument('1.0','iso-8859-1');
with json_encode() and JSON.parse(); to javascript. But it didn't help too.
I don't know what else can I do. Can you help me?
You've created an element, but you haven't inserted it anywhere into the document. You need to figure out the appropriate place to put it into the DOM and then do so.
For example, if you have existing HTML of
<div class="main">
</div>
you can create a <p> and insert it to the bottom of the .main with
const main = document.querySelector('.main');
const line = document.createElement('p');
line.textContent = 'anytext';
main.appendChild(line);

Javascript: Create a new div in <body> tag

This is going to be hard to explain but I will do my best. I want to write a Javascript function that takes two parameters (title, content) and creates a <div> tag in the <body> tag. The <div> tag should look like this.
<div>
<h2>title</h2>
<p>content</p>
</div>
My javascript code looks like this:
function addElement (title, content) {
var newDiv = document.createElement("div");
var newH2 = document.createElement("h2");
var title = document.createTextNode(header);
newH2.appendChild(title);
var p = document.createElement("p");
var post = document.createTextNode(entry);
p.appendChild(post);
newDiv.appendChild(newH2);
newDiv.appendChild(p);
// Missing codes here...
}
I dont know how to finish my method. Because of I have almost hundreds of tags inside my page and I want this new tags (when a user makes a new input) will appear on same place somewhere in the middle of the html code page in order to keep things organized.
If you would like to use jQuery take a look at this fiddle: http://jsfiddle.net/panpymq2/
In my fiddle I am binding to a button press. Then I call a method that appends new generated html to the body of the page. You can enter change where you are appending the new HTML with CSS3 selectors. just modify the $("insert selector there").append...
UPDATE
As per the new requirements I have updated my fiddle: http://jsfiddle.net/panpymq2/1/
I now prepend the new html to the document.
You already know how to add elements as children of other elements. That's what you used to add the h2 and p to the div. You could use the same appendChild to add the div to the document:
document.body.appendChild(newDiv);
But you don't want it at the bottom of the page--you want it "in the middle of the html code page". One straightforward way to do this is to add the newDiv to a container that's in the right place, in the middle of the page.
You'd first create this container in the page HTML:
<!doctype html>
<body>
<p>stuff before</p>
<div id="container"></div>
<p>stuff after</p>
</body>
Then, finish off addElement with:
document.getElementById('container').appendChild(newDiv);
One way would be if addElement took a third parameter which is the sibling/parent you want to insert your new element next to/within.
function addElement(title, content, target) {
...
target.insertAdjacentElement('afterend', newDiv);
// or
target.appendChild(newDiv);
}
I think this is as much of an HTML as a CSS problem. I've had the same issue.
One way of solving this problem is to make an (extra) container <div> as follows:
<div id="outer_container_elems">
<div id="inner_container_elems">
...
</div>
</div>
And append to inner_container_elems
Hope this helps!

Javascript - Insert element at script position

How do I insert element at script location (not to rely on div's id or class), for example
<div class="div">
<script src='//remotehost/js/addDivSayHello.js'></script>
</div>
where addDivSayHello.js will insert div child <div>hello</div>, result example:
<div class="div">
<div>hello</div>
<script src='//remotehost/js/addDivSayHello.js'></script>
</div>
I tried searching inside Stackoverflow but found nothing.
You can use insertBefore method. Something like this:
var div = document.createElement('div'), // Create a new div
script = document.scripts[document.scripts.length - 1]; // A reference to the currently running script
div.innerHTML = 'Hello'; // Add some content to the newly-created div
script.parentElement.insertBefore(div, script); // Add the newly-created div to the page
A live demo at jsFiddle. Notice, that you can use external scripts as well.
You could use insertAdjacentHTML: https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML
var node = document.querySelector('script[src="js/addDivSayHello.js"]');
node.insertAdjacentHTML('beforebegin', '<div>hello</div>');
$("div.div").prepend('<div>hello</div>');
You have to call the script at some point
i like to use jquery to add an element http://api.jquery.com/append/
you have to say where do you want to add :
$(".div")
and what should happen there:
.append("<div>Hello</div>")
so its look like that:
$(".div").append("<div>Hello</div>")
Another solution that doesn't wrap everything inside a div and that can be re-used several times without implications:
function insertHtmlToDocumentAtCurrentScriptPosition(htmlStr)
{
var scriptTag = document.getElementsByTagName('script');
scriptTag = scriptTag[scriptTag.length - 1];
var parentTag = scriptTag.parentNode;
parentTag.innerHTML += htmlStr;
}
The function takes html as string, so call it like:
insertHtmlToDocumentAtCurrentScriptPosition(`<p>Hello</p>`);

.html() and .append() without jQuery

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>

Javascript: Dynamic Generation of a Div

I have several vertically stacks divs and I want to have a div appear when I click a button within each of these divs. The div that I want to appear will be the exact same for each appearance with the exception of an id associating it with the outer div. How do I do this in Javascript?
I assume I should use the createElement() within Javascript, but how do I append it to the end of a specific element. Also, when creating an element, I have to hardcode the html in the Javascript file. Is there anyway to leave the element within the html design file. I want to seperate design from code as much as possible.
Clone Node
var clone = myDiv.cloneNode();
Example (live demo):
HTML
<div>
<input type="button" onclick="functionClone(this);" value="Dolly"/>
<input type="button" onclick="functionClone(this);" value="Dolly_1"/>
</div>
Javascript:
functionClone = function(subject){
var clonenode = subject.cloneNode(true);
subject.value = subject.value + '\'s been cloned!';
subject.disabled = true;
insertElementAfter(subject, clonenode);
}
insertElementAfter = function(subject, newElement){
subject.parentNode.insertBefore(newElement,subject.nextSibling);
}
To append an element below your div use this:
subject.parentNode.appendChild(clonenode)

Categories

Resources