I have a page that requires user input then it will execute some javascript and populate fields on the page. Part of this includes calling a perl script that will run and get data from another page check that against the input from the user. The number of items that the perl script will return could be anywhere from zero to ten or even more. To handle this I have written some javascript to append each item into a list on my html page.
The problem I am coming across is that it seems to work perfectly fine in Safari and chrome, but does not seem to want to work in internet explorer 6 or 7. The major issue here is that most of the people that will be using this will be on internet explorer. I have no errors in my javascript code.
<div id='testDiv'><ul></ul></div>
then I just have my javascript replace the instance off </ul> in the div with
<li>blah blah blah</li></ul>
and have that repeat for each time an item needs to be added to the list. Everything else on the page works fine, and there are even new line for where the new list items show be. However it does not show any text there.
is there something I am doing wrong or is internet explorer not rendering this correctly?
EDIT: added the requested information.
var dateList = document.getElementById('testDiv').innerHTML;
var insertToList = "<li><div>blah blah blah</div></li></ul>";
dateList = dateList.replace('</ul>', insertToList);
document.getElementById('testDiv').innerHTML = dateList;
I have this in a loop to cycle through the results and add results to the list as appropriate. Unfortunately, I cannot link you the page since this is an internal project.
Depending on what you are using for your selector engine, IE is different. I recommend using jQuery for selecting and replacing content as it handles browser differences for you.
In IE6 testDiv.innerHTML is <UL></UL>. Note the upper-case tags.
dateList.replace('</ul>', ...) can't find anything that matches so it doesn't perform the replace.
A better approach would be to get a reference to the list (ul) element and append the HTML there.
var ulRef = document.getElementById('testDiv').getElementsByTagName("ul")[0];
ulRef.innerHTML += "<li><div>blah blah blah</div></li>";
Related
I'm making a Chrome extension that replaces certain text on a page with new text and a link. To do this I'm using document.body.innerHTML, which I've read breaks the DOM. When the extension is enabled it seems to break the loading of YouTube videos and pages at codepen.io. I've tried to fix this by excluding YouTube and codepen in the manifest, and by filtering them out in the code below, but it doesn't seem to be working.
Can anyone suggest an alternative to using document.body.innerHTML or see other problems in my code that may be breaking page loads? Thanks.
var texts=["some text","more text"];
if(!window.location.href.includes("www.google.com")||!window.location.href.includes("youtube.com")||!window.location.href.includes("codepen.io")){
for(var i=0;i<texts.length;i++){
if(document.documentElement.textContent || document.documentElement.innerText.includes(texts[i])){
var regex = new RegExp(texts[i],'g');
document.body.innerHTML = document.body.innerHTML.replace(regex,
"<a href='https://www.somesite.org'>replacement text</a>");
}
}
}
Using innerHTML to do this is like using a shotgun to do brain surgery. Not to mention that this can even result in invalid HTML. You will end up having to whitelist every single website that uses any JavaScript at this rate, which is obviously not feasible.
The correct way to do it is to not touch innerHTML at all. Recursively iterate through all the DOM nodes (using firstChild, nextSibling) on the page and look for matches in text nodes. When you find one, replace that single node (replaceChild) with your link (createElement), and new text nodes (createTextNode, appendChild, insertBefore) for any leftover bits.
Essentially you will want to look for a node like:
Text: this is some text that should be linked
And programmatically replace it with nodes like:
Text: this is
Element: a href="..."
Text: replacement text
Text: that should be linked
Additionally if you want to support websites that generate content with JavaScript you'll have to run this replacement process on dynamically inserted content as well. A MutationObserver would be one way to do that, but bear in mind this will probably slow down websites.
I saw a few posts similar to my problem and tried the solutions offered, but I'm still having issues with IE8 & IE9 and 'selectedIndex'. This code returns my variable answerSubmitted as 'undefined':
var answerSubmitted = document.getElementById("DropDown-Answers").selectedIndex;
The above works perfectly in all other browsers. Based on another post here, I also tried this:
var answerSubmitted = document.getElementById("DropDown-Answers").value;
Still the same results - works elsewhere, but not in IE8 or IE9. I've verified that IE is recognizing that particular element by its ID.
Any guidance here?
MORE INFO:
I'm creating the drop down menu dynamically by going thru a loop and adding variable text between the option and /option tags, like so (note that 'tempRandom' is a random number updated each time thru the loop):
tempMenuText = tempMenuText + "<option>" + Answers[tempRandom] + "</option>";
The results are surrounded by the form an select tags, then I update the innerHTML of my element. This works and generates a working drop down menu. But... perhaps this is a clue: when I put a test with the innerHTML of the menu element into another element to view it, it shows as empty. It's as though IE is not seeing that there is HTML in the element, thinks it is null, and therefore 'selectedIndex' fails as null.
This is solved. It turns out it was my error in how I was referring to the ID of the selected item. An associate explained that .selectedIndex only works (in IE, at least), when the ID within the 'select' tag is correct. If not, it returns null, which is what was originally happening. All is good now. Thanks for the suggestions.
I have some crazy app done almost 100% by manipulating the DOM and I find myself in the unfortunate position of changing something in it. As there are probably around 100 different scripts that do God knows what, I have no clue in which file should I look to make my changes. So, I want to ask, is there a way (using Firebug maybe or something similar) to know where a specific piece of html was generated? I'm a C developer, so I'm not very good at this, it drives me crazy.
Are all the elements added at the page load, or partially in the response to the user input? (clicking etc.)
for stuff added with the response to your actions, you can use Firebug's "Break On Next" button in the "Script" tab. To active BON you have to click it, or, in just-shipped Firebug 1.10.0a8, use keyboard shortcut ALT-CTRL-B (useful when you have event listeners bound to mouse movements). Then, when any piece of JS is going to be executed in reaction to your click etc., you will hit a breakpoint.
for stuff added at page load time, you may use the trick of extending the native functions (this might sound crazy - yeah it is, don't do it in production!) like appendChild, insertBefore, replaceChild. Just insert the appropriate code at the very top of your main HTML file, so all the code below will "see" the change.
Unfortunately, this does not work in Firefox due to a bug. But works in Opera and I guess in Chrome as well.
When you extend the native function, you can inject any code before really adding the node to the page. For instance, call console.log or create a breakpoint, to inspect the current page state. You can try playing with breakpoints to see the available variables properties inside those function to adjust what you push to console.log.
For this code:
<!doctype html>
<html>
<head>
<script type="text/javascript">
// this should work in Firefox but it does not -- https://bugzilla.mozilla.org/show_bug.cgi?id=618379
// works at least in Opera, probably Chrome too
Node.prototype._appendChild = Node.prototype.appendChild;
Node.prototype.appendChild = function(child) {
console.log("appending " + child + " to " + this);
return this._appendChild(child); // call the original function with the original parameters
}
// this works in Firefox
document._createElement = document.createElement;
document.createElement = function(tagName){
console.log("creating " + tagName);
return this._createElement(tagName);
}
</script>
</head>
<body>
<script type="text/javascript">
var p = document.createElement("p");
p.appendChild( document.createTextNode("abc"));
document.body.appendChild(p);
</script>
</body>
</html>
Opera outputs:
creating p appendChild.html:14
appending [object Text] to [object HTMLParagraphElement] appendChild.html:7
appending [object HTMLParagraphElement] to [object HTMLBodyElement] appendChild.html:7
To overcome the weakness of Firefox (that you can't override appendChild), you may use the trick: place the code below instead in the top of your HTML
<script>
Node.prototype._appendChild = function(child) {
console.log("appending " + child + " to " + this);
return this.appendChild(child)
};
</script>
and then, use Fiddler proxy by creating auto-responders (WMV tutorial, 9.9 MB) where you manually replace all calls to .appendChild with ._appendChild (you can use Notepad++ for "find replace in all opened files"). Creating auto-responders and hand-tampering requests can be mundane, but it's extremely powerful. To quickly create auto-responder rule, load the page when Fiddler is active, then drag'n'drop files as in the picture below. For each file, right click and choose "Generate File" from menu (this will put a file on the desktop) or create a file by yourself in different location. (it's good to open Fiddler-generated files and remove response headers from them; BTW "Generate file" puts real contents only if the response header was 200, so make sure to load the page with CTRL-F5 to skip the cache).
In Chrome you can inspect an element and right click on it. This menu gives you some options to break when something below the element is changed or when it's own attributes change. Maybe one of those breakpoints will find what you are looking for?
Assuming you've got access to the raw (hopefully un-minified/obfuscated) JS files, maybe just search them for text strings related to DOM manipulation and/or attributes of the node you're trying to find the creation of? I'd try things like "appendChild" "createElement" and the node's ID/class names.
You could also set break points all over the script files, and step through them as the page loads to help you narrow down where to look. Might help to start by just "pausing" the JS execution and stepping through from the very beginning.
If you can share the code (a link to the live site would do fine) I'd be happy to take a look.
If you are using the jQuery framework in your javascript to make the DOM changes then you may find the fireQuery plugin for FireBug in the firefox browser may get you the information you need.
Example:
It adds additional information to the standard HTML view by superimposing additional jquery element information to the display to provide a deeper insight into how your javascript is amending the page content.
I hope that helps you out.
I have a js replace function to replace text next to two radio buttons on a pre set form.
Script is as follows.
document.body.innerHTML=document.body.innerHTML.replace("Payment by <b>Moneybookers</b>
e-wallet<br>","");
document.body.innerHTML=document.body.innerHTML.replace("Maestro, Visa and other credit/debit cards by <b>Moneybookers</b>","Pago con Diners Club, Mastercard o Visa");}onload=x;
The script works fine in Chrome and Firefox, however, the script is not actioned in Explorer.
I believe it has something to do with there being , / - within the text I am replacing? When I use the function to replace text with no , / - in the text - it works fine in explorer, however, for example when I try to replace text.. - "Maestro, Visa and other credit/debit cards by Moneybookers" this does not work in explorer.. I'm assuming because of the coma and forward slash. Honestly I've tried everything but just can not get this to work. Any help would be greatly appreciated!!
Not sure whether it's related (I'm a Mac user without IE) but you shouldn't use multiline strings. Use \n instead.
What is returned by innerHTML varies from one browser to an other, because there is no standard about it (the content will be the same, but the way it's displayed can be different). Doing replace like that is likely to fail on some browser. You should just take an other approach to do your replace.
A better approach would be to wrap the text you want to replace with a span, this way you can more easily target the content you want to replace.
<span id="thatFirstThing">Payment by <b>Moneybookers</b>e-wallet<br></span>
An after you can do
document.getElementById("thatFirstThing").innerHTML = "";
P.S.: Doing innerHTML replace on the body also has a huge side-effect. Since you are replacing the content of your hole page. All the event handler that where bind on your page will disappear.
Edit: If you can't modify the HTML page, it's a little bit more tricky, because the DOM is not well adapted to do such thing. What you could do is to target parent element by navigating through the DOM with document.getElementById and childNodes. And once you have your parent element just write the new content you want, without doing replace.
In the end it would look something like this :
document.getElementById("someSection").childNodes[0].childNodes[1].childNodes[0].innerHTML = "";
I'm loading a string via AJAX that reads like
<style>[some definitions]</style>
<h1>Lots of Markup</h1>
<p>follows here</p>
Using Webkit/Gecko everything works as expected — the markup is inserted, styles are applied. In IE (8) though the style-definitions are ignored. Actually, if you use the developer tools they are gone.
You can see in this JS-Fiddle that it doesn't work: http://jsfiddle.net/J4Yzr/
Also, I've seen that trick that you create a temporary DOM-Object, set it's innerHTML to your markup and extract your markup as DOM-Objects from your temporary element. That doesn't work with style tags (if I did it right, I'm using prototypeJS):
var text = '<style>h1{color:red;}</style> style added',
el = new Element('div').update(text);
console.log(el.firstChild);
//is a HTMLStyleElement in Webkit but a [object Text] in IE
Does anyone have a suggestion how to properly apply the <style> in IE if you get it from such a string?
I had the same problem, so I tried your solution, but guess what? When I stripped the out after rendering markup retrieved via Ajax, the tags disappeared from the DOM! Back to square one.
So my solution is to prepend this instead:
<hr style='display:none'/>
Which did the trick nicely. Thank you so much for solving this issue.
Ok, it's crazy. Add a <br/>-Tag in front of your string and it works in Internet Explorer.
<br/><style>[some definitions]</style><h1>Lots of Markup</h1>
You don't even need to create that temporary DOM-Object to insert code into. Just append it in your site.
What I'm doing now it insert the code with a <br/>-Tag and remove the <br/> afterwards. It's messy but it works.