Omer
Omer

Reputation: 661

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!

Upvotes: 4

Views: 350

Answers (2)

Jamie Dixon
Jamie Dixon

Reputation: 54001

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

Upvotes: 3

Ilia Choly
Ilia Choly

Reputation: 18557

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

Upvotes: 0

Related Questions