I have an iframe element which I create dynamically. Where should I append this iframe if I am not sure if there is a body tag in the html or not ? I was thinking of appending this as child of html tags like div which I have to create dynamically too. But I need to append the div somewhere. Again I am not sure where to append the div.
You have to insert it in a body tag. So if there is no body tag, just insert a body tag after the head element, and the iframe tag in the body tag.
I guess you must do it like this.
Check if body exists, If it does not exists create it.
var dom = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
if(!document.body)
{
var body = dom.createElement("body");
body.innerHTML = "<iframe></iframe>";
dom.firstChild.appendChild(body);
}
else
{
document.body.innerHTML = "<iframe></iframe>";
}
Your question seems to be asking how to accommodate non-standard HTML documents. If you absolutely must, and cannot insist that the document provider make their documents standards-compliant, I would check for a body tag and, if present, append to that. If not available, I'd test for the html element and append to that. Beyond that, I'd decline to serve the other party in this regard.
if (document.getElementsByTagName('body')) {
...
} else if {document.getElementsByTagName('html')) {
...
} else {
console.log("We're sorry, but your document is poorly constructed
and we won't be serving you today.");
}
Related
Hello my question is how to write inside script called parent element with document.write when parent element is unknown
You may consider this as advertising script
For example:
<div>
<script src="http://www.pokemonpets.com/scripts/ads_simple.js"></script>
</div>
My script code below but not working right now
document.write('<a title="Bedava Pokemon Online Oyunu" target="_blank" href="http://www.pokemonpets.com/Register"><img src="http://orig04.deviantart.net/58d0/f/2015/213/8/4/pokemonpets_by_monstermmorpg-d93plr1.png" /></a>');
So somehow i have to make it work without knowing parent element or without knowing whether page has JQuery or not.
How does advertising companies handle this?
You don't want to use document.write, you want to find your script tag and replace it with your new content. You can do that by looking for a script tag with your URL, then having it's parent replace it.
scripts = document.getElementsByTagName("script");
for(var i in scripts){
if(scripts[i].src.indexOf('//www.pokemonpets.com/scripts/ads_simple.js') !== -1){
var wrapper = document.createElement('div');
wrapper.innerHTML = '<a title="Bedava Pokemon Online Oyunu" target="_blank" href="http://www.pokemonpets.com/Register"><img src="http://orig04.deviantart.net/58d0/f/2015/213/8/4/pokemonpets_by_monstermmorpg-d93plr1.png" /></a>';
scripts[i].parentElement.replaceChild(wrapper,scripts[i]);
}
}
This is totally untested, not even for syntax, so you might need to fiddle with it a bit.
I am tasked with converting hundreds of Word document pages into a knowledge base html application. This means copying and pasting the HTML of the word document into an editor like Notepad++ and cleaning it up. (Since it is internal document I need to convert, I cannot use online converters).
I have been able to do most of what I need with a javascript function that works "onload" of the body tag. I then copy the resulting HTML into my application framework.
Here is part of the function I wrote: (it shows only code for removing attributes of div and p tags but works for all html tags in the document)
function removeatts() //this function will remove all attributes from all elements and also remove empty span elements
{//for removing div tag attributes
var divs=document.getElementsByTagName('div'); //look at all div tags
var divnum=divs.length; //number of div tags on the page
for (var i=0; i<divnum; i++) //run through all the div tags
{//remove attributes for each div tag
divs[i].removeAttribute("class");
divs[i].removeAttribute("id");
divs[i].removeAttribute("name");
divs[i].removeAttribute("style");
divs[i].removeAttribute("lang");
}
//for removing p tag attributes
var ps=document.getElementsByTagName('p'); //look at all p tags
var pnum=ps.length; //number of p tags on the page
for (var i=0; i<pnum; i++) //run through all the p tags
{//remove attributes for each p tag
var para=ps[i].innerHTML;
if (para.length!==0) //ie if there is content inside the p tag
{
ps[i].removeAttribute("class");
ps[i].removeAttribute("id");
ps[i].removeAttribute("name");
ps[i].removeAttribute("style");
ps[i].removeAttribute("lang");
}
else
{//remove empty p tag
ps[i].remove() ;
}
if (para=="<o:p></o:p>" || para=="<o:p> </o:p>" || para=="<o:p> </o:p>")
{
ps[i].remove() ;
}
}
The first problem I encountered is that if I included the if (para=="<o:p></o:p>" || para=="<o:p> </o:p>" || para=="<o:p> </o:p>") part in an else if statement, the whole function stopped executing.
However, without the if (para=="<o:p></o:p>" || para=="<o:p> </o:p>" || para=="<o:p> </o:p>") part, the function does exactly what it is supposed to.
If, however, I keep it the way it is right now, it does some of what I want it to do.
The trouble occurs over some of the Word generated html that looks like this:
<p class=MsoNormal style='mso-margin-top-alt:auto;mso-margin-bottom-alt:auto; margin-
left:.25in;text-align:justify;text-indent:-.25in;line-height:150%;
mso-list:l0 level1 lfo1;tab-stops:list .75in'>
<![if !supportLists]><span style='font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:Symbol;color:black'><span style='mso-list:Ignore'>·
<span style='font:7.0pt "Times New Roman"'>
</span></span></span>
<![endif]><span style='font-family:"Arial","sans-serif";mso-fareast-font-family:Calibri;color:black'>
SOME TEXT.<span style='mso-spacerun:yes'> </span>SOME MORE TEXT.<span style='mso-spacerun:yes'> </span>EVEN MORE TEXT.
<span style='mso-spacerun:yes'> </span>BLAH BLAH BLAH.<o:p></o:p></span></p>
<p><o:p></o:p></p>
Notice the <o:p></o:p> in the last two lines..... This is not getting removed either when treated as plain text or if I write code for it in the function just like the divs and paragraphs as shown in the function above. When I run the function on this, I get
<p>
<![if !supportLists]><span>·
<span>
</span></span></span>
<![endif]><span>
SOME TEXT.<span> </span>SOME MORE TEXT.<span> </span>EVEN MORE TEXT.
<span> </span>BLAH BLAH BLAH.<o:p></o:p></span></p>
<p><o:p></o:p></p>
I have looked around but cannot find any information about whether javascript works the same on known html tags and on something like this that follows the principle of opening and closing tags but doesn't match known HTML tags!
Any ideas about a workaround would be greatly appreciated!
Javascript has no special processing of HTML tags in javascript strings. It honestly doesn't know anything about HTML in the string.
More likely your issue is trying to compare .innerHTML of a tag to a predetermined string. You cannot and should not do that because there is no guarentee for the format of .innerHTML. As there are hundreds of ways that the same HTML can be formatted and some browsers don't remember the original HTML, but reconstitue it when you ask for .innerHTML, you simply can't do that type of string comparison.
To be sure of your comparison, you will have to actually parse the HTML (at least with some sort of crude parser which perhaps could even be a regex) to see if it matches what you want because you can't rely on optional spacing or optional capitilization in a direct string comparison.
Or, perhaps even better, since your HTML is already parsed, why not just look at the actual HTML objects themselves and see if you have what you want there. You shouldn't even have to remove all those attributes then.
It's not Javascript that is unhappy with the unknown tags. It's the browser.
For JS it's simply a string. So, if it's a very specific case that you don't need <o:p> in particular then you could just remove it by running it with a regex itself.
para.replace(/<[/]?o:p>/ig, "");
But if there are many more, I would strongly suggest you to get familiar with XSLT transformation.
The first problem I encountered is that if I included the if (para=="<o:p></o:p>" || para=="<o:p> </o:p>" || para=="<o:p> </o:p>")
part in an else if statement, the whole function stopped executing.
This is because you cannot have else if after else.
Notice the <o:p></o:p> in the last two lines..... This is not getting removed
I cannot confirm that. When I run your function it removes the <o:p> inside the <p>, as it is supposed to. The <o:p> within the <span> is not processed, because your function does not do that.
If you want to remove all <o:p>s, try
[].forEach.call(document.querySelectorAll('o\\:p'), function (el) {
el.remove();
});
After that, you may want to remove empty <p>s like this
[].forEach.call(document.querySelectorAll('p'), function (el) {
if (!el.childNodes.length) {
el.remove();
}
});
I have an html element on my website that is being put there beyond my control and I need to remove it using javascript/jquery. The HTML tag is consistent and on every page, it looks like this:
<img src="https://myimage.com/myimage.jpg" style="cursor:pointer;border:none;">
how do I remove it? The image has no ID. Thanks so much in advance!
You can remove it like this:
jQuery("img[src='https://myimage.com/myimage.jpg']").remove();
Be sure that that code is in a script tag below the relevant image in the markup of the page. If the image is being added dynamically after the page markup has been parsed, you may have to be more crafty:
(function() {
function removeImage() {
var img = jQuery("img[src='https://myimage.com/myimage.jpg']");
if (img.length) {
// It's there now, remove it
img.remove();
}
else {
// Not there yet, check again in a quarter of a second
setTimeout(removeImage, 250);
}
}
removeImage(); // Start the process
})();
Note: You're removing an element, not a tag. Tags are markup (text). Elements are the result of tags being parsed and created by the browser.
use
$("img[src='https://myimage.com/myimage.jpg']").remove();
That will hide that image
Here you go
$("img[src='https://www.google.com/images/srpr/logo11w.png']").remove();
http://jsfiddle.net/bowenac/GD64n/
Mind explaining what the image is or post a live link? This will remove it from displaying but will not fix the source of the problem if this is some kind of hack placing this code into your files...
No jQuery, plain JS:
var img = document.querySelector('img[src="https://myimage.com/myimage.jpg"]');
if (img) {
img.parentNode.removeChild(img);
}
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"));
})
);
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>