JS works in IE, Safari, Chrome but not in Firefox? - javascript

Most my work is done running on Webkit stuff and using Chrome's dev tools. But this code doesn't run in Firefox; it doesn't even throw a console error so I have no idea what's wrong. Any ideas. I'm sure its terribly easy. My code is designed to look throw a div for a specific syntax "t_" "r_" which are references to an external document; I'm trying to find all said references and replace them with hyperlink. I"m a novice JS coder so sorry for the naiveness you'll undoubtedly see in here.
(I'm using FF 22.0)
<!DOCTYPE html>
<html>
<head>
<script>
function pre_forwarder(){ //First Step
patt_1=/\[r_/g;
patt_2=/\[t_/g;
patt_S_and_R_1 = "[r_";
patt_S_and_R_2 = "[t_";
forwarder(patt_1,patt_S_and_R_1);
forwarder(patt_2,patt_S_and_R_2);
}
function forwarder(Pattern,Pre_SearchReplace){
rule_string = document.getElementById("divid");
rule_string = rule_string.innerText;
var patt1 = Pattern;
while (patt1.test(rule_string)==true)
{
begin_string = patt1.lastIndex;
fullpar_string = patt1.lastIndex + 5;
partial_string = rule_string.slice(begin_string,fullpar_string); //5 characters
//alert("partial_string-"+partial_string);
refined_string_end = partial_string.indexOf("]");
refined_str = partial_string.slice(0,refined_string_end); //raw number
full_str = Pre_SearchReplace+refined_str+"]"; //restructured
SectionNum = refined_str;
SearchReplace = full_str; //Variable to pass to parse()
//alert("S&R="+SearchReplace+" >> full_string-"+full_str);
//alert("S&R"+SearchReplace+">>SecNum-"+SectionNum+">>Pre-Search-"+Pre_SearchReplace);
Parse(SearchReplace,SectionNum,Pre_SearchReplace);
}
//var patt_end=/\[t_/g;
}
function Parse(SearchReplace,SectionNum,Pre_SearchReplace){
if (Pre_SearchReplace == patt_S_and_R_1){
ref_URL = "UEB_Ref.html#";
}else if (Pre_SearchReplace == patt_S_and_R_2){
ref_URL = "UEB_Tech.html#";
}
linkCreate = 'Link to ch-'+SectionNum+' ';
document.getElementById("divid").innerHTML = document.getElementById("divid").innerHTML.replace(SearchReplace, linkCreate);
}
function Dude(SectionNum){
alert(SectionNum);
}
</script>
</head>
<body onload="pre_forwarder();">
<button onclick="pre_forwarder();">
New Tool</button>
<div id="divid">
hello [dude] ok the end [r_12.1][r_7] [r_22]
<br>bro try this [t_15.3][t_6] [t_5.5]
</div>
<div id="hyperlink">
</div>
</body>
</html>

You've rule_string = rule_string.innerText; at line 15. FF doesn't know innerText, you need to use textContent, or a fix like:
rule_string = rule_string.innerText || rule_string.textContent;
A live demo at jsFiddle.
As a side note: Looks like your app is based on global variables. Please don't use this kind of programming technique. It'll do the job, as long as there's not much of code, but when your apps are getting larger, you'll lose control over a ton of global variables.
For starters, you can read JavaScript Guide at MDN, especially chapters 4, 8 and 9.

Related

Internet Explorer 8 error, Object Required (JavaScript)

I wrote a todo in chrome that works fine. I tested it in IE8 and it didn't work. So I made a new file to write specifically in IE8, and I can't even get a simple function to work properly. I would like help in finding out what i'm doing wrong. Thank you to anyone that can school me on this.
HTML
<body>
<p>Home</p>
<form id="form1">
<input type="text" id="inItemText" />
</form>
<button id="btn1" onclick="doIt()">Press Here</button>
<p id="p1"></p>
</body>
Javascript
var inItemText = document.getElementById("inItemText");
function doIt() {
var itemText;
itemText = inItemText.value;
document.getElementById("p1").innerHTML = itemText;
form1.reset();
}
Make sure you do the inItemText assignment after the DOM has been loaded. Otherwise, document.getElementById("inItemText") won't find the element, because it doesn't exist yet.
Either put it at the end of the <body>, or use window.onload:
var inItemText;
window.onload = function() {
inItemText = document.getElementById("inItemText");
};
You're getting that error because inItemText isn't defined. Use document.getElementById('inItemText').
I think the issue is in this line:
itemText = inItemText.value;
You need to declare "inItemText" as a variable.
Perhaps replace it with:
itemText = document.getElementById("inItemText").value

Javascript not rendering - Blank head

There's something wrong with my script, it doesn't render the JS correctly. I tried to pinpoint the problem but cannot find any typo. If i load the page, the tag is blank, making all css & other JS disabled. But suprisingly the data is loader correctly. If i remove the script, everything went to normal.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery-1.9.1.js"></script>
<script src="jquery-ui.js"></script>
<script>
// Create a connection to the file.
var Connect = new XMLHttpRequest();
// Define which file to open and
// send the request.
Connect.open("GET", "Customers.xml", false);
Connect.setRequestHeader("Content-Type", "text/xml");
Connect.send(null);
// Place the response in an XML document.
var TheDocument = Connect.responseXML;
// Place the root node in an element.
var Customers = TheDocument.childNodes[0];
// Retrieve each customer in turn.
$("#middle").ready( function () {
document.write("<ul class='product'>");
for (var i = 0; i < Customers.children.length; i++)
{
var dul = "wawa"+[i];
//document.getElementById(dul).addEventListener('click', storeData, false);
var Customer = Customers.children[i];
// Access each of the data values.
var Pic = Customer.getElementsByTagName("pic");
var Name = Customer.getElementsByTagName("name");
var Age = Customer.getElementsByTagName("tipe");
var sex = Customer.getElementsByTagName("country");
var checked = window.localStorage.getItem("selected"+i);
// Write the data to the page.
document.write("<li><img href='./pic/");
document.write(Pic[0].textContent.toString());
document.write(".jpg'><a href='display.html?id="+i+"'>");
document.write(Name[0].textContent.toString());
document.write("</a><div class='age'>");
document.write(Age[0].textContent.toString());
document.write("</div><div class='sex'>");
document.write(sex[0].textContent.toString());
document.write("</div><div class='cex'>");
document.write("<input name='checkbox' type='checkbox' id='wawa_"+i+"'");
if (!checked) {
document.write(" onClick='cbChanged(this, "+i+")'");
} else {
document.write("checked onClick='cbChanged(this, "+i+")'");
}
document.write("></div></li>");
}
document.write("</ul>");
});
function cbChanged(checkboxElem, x) {
if (checkboxElem.checked) {
window.localStorage.setItem("selected"+x, x);
alert("That box was checked.");
} else {
window.localStorage.removeItem("selected"+x);
alert("That box was unchecked.");
}
}
</script>
</head>
<body>
<div class="container">
<div class="content" id="middle">
</div>
<div class="content" id="footer">
</div>
</div>
</body>
</html>
Ok here's the full source.
You don't close the HTML img tag right
Change
document.write("<li><img href='./pic/");
document.write(Pic[0].textContent.toString());
document.write("'.jpg><a href='display.html?id="+i+"'>");
// ^ this quote
To
document.write("<li><img href='./pic/");
document.write(Pic[0].textContent.toString());
document.write(".jpg'><a href='display.html?id="+i+"'>");
// ^ should be here
If you open the developer console you can usually see where errors like this take place. It will also output and javascript errors that you come across so it will make that part a whole lot easier. Do you have any errors in your console?
The dev consoles are:
Chrome: It is built it.
Firefox: Firebug
Safari: It's built it
EDIT:
Don't do var functionName = function() {..} unless you know about how hoisting works. This is contributing to you problem so change
cbChanged = function(checkboxElem, x) {
if (checkboxElem.checked) {
window.localStorage.setItem("selected"+x, x);
alert("That box was checked.");
} else {
window.localStorage.removeItem("selected"+x);
alert("That box was unchecked.");
}
}
To
function cbChanged(checkboxElem, x) {
if (checkboxElem.checked) {
window.localStorage.setItem("selected"+x, x);
alert("That box was checked.");
} else {
window.localStorage.removeItem("selected"+x);
alert("That box was unchecked.");
}
}
Without the above changes the function cbChanged is not hoisted. So if you call it before it is reached you will get an error.
There are several other things that stand out to me on this. You might want to spend some more time on your javascript fundamentals. Read up on why document.write is a bad thing. Try removing parts of the script to narrow down what is causing the problem. It would have made this easier to fix if you had made a fiddle.

Accessing lastNode value in XML using JavaScript is not working in Chrome

I am a novice to JavaScript programming with XML. I tried the following example from the book "Inside XML", but couldn't able to get it running.
Following is the HTML code with JavaScript:
<HTML>
<HEAD>
<TITLE>
Reading XML element values
</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function readXMLDocument()
{
var xmldoc, meetingsNode, meetingNode, peopleNode
var first_nameNode, last_nameNode, outputText
<!--xmldoc = new ActiveXObject("Microsoft.XMLDOM")-->
<!--xmldoc.load("meetings.xml")-->
parser=new DOMParser();
xmldoc=parser.parseFromString("meetings.xml","text/xml");
meetingsNode = xmldoc.documentElement
meetingNode = meetingsNode.firstChild
peopleNode = meetingNode.lastChild
personNode = xmldoc.getElementsByTagName("PEOPLE").lastChild
first_nameNode = personNode.firstChild
last_nameNode = first_nameNode.nextSibling
outputText = "Third name: " +
first_nameNode.lastChild.nodeValue + ' '
+ last_nameNode.lastChild.nodeValue
messageDIV.innerHTML=outputText
}
</SCRIPT>
</HEAD>
<BODY>
<CENTER>
<H1>
Reading XML element values
</H1>
<INPUT TYPE="BUTTON" VALUE="Get the name of the third person"
ONCLICK="readXMLDocument()">
<P>
<DIV ID="messageDIV"></DIV>
</CENTER>
</BODY>
</HTML>
Following is the XML code used:
<?xml version="1.0"?>
<MEETINGS>
<MEETING TYPE="informal">
<MEETING_TITLE>XML In The Real World</MEETING_TITLE>
<MEETING_NUMBER>2079</MEETING_NUMBER>
<SUBJECT>XML</SUBJECT>
<DATE>6/1/2002</DATE>
<PEOPLE>
<PERSON ATTENDANCE="present">
<FIRST_NAME>Edward</FIRST_NAME>
<LAST_NAME>Samson</LAST_NAME>
</PERSON>
<PERSON ATTENDANCE="absent">
<FIRST_NAME>Ernestine</FIRST_NAME>
<LAST_NAME>Johnson</LAST_NAME>
</PERSON>
<PERSON ATTENDANCE="present">
<FIRST_NAME>Betty</FIRST_NAME>
<LAST_NAME>Richardson</LAST_NAME>
</PERSON>
</PEOPLE>
</MEETING>
</MEETINGS>
But, when I run the code in Chrome, I get the following error:
Uncaught TypeError: Cannot read property 'nodeValue' of null
Please help me to resolve this issue. Thank you in advance.
I used Firefox with the firebug plugin to debug but you can use Chrome without any plugins. After loading the page you can press F12 to open the devtools. In the console tab you can see the output of your logs, warnings, errors and there is a command line to execute JavaScript.
Sometimes I make a variable global (check in the code for variable a) so I can type a. in the command line and see what properties it has.
One of the problems was that a node includes whitespace so the last node is a textNode containing whitespace in many cases. You should also try to end your statements with ;
Here is the code half debugged, hope it helps:
<textarea id="txt">your xml content</textarea>
function readXMLDocument(){
var xmldoc, meetingsNode, meetingNode, peopleNode,
first_nameNode, last_nameNode, outputText;
<!--xmldoc = new ActiveXObject("Microsoft.XMLDOM")-->
<!--xmldoc.load("meetings.xml")-->
parser=new DOMParser();
xmldoc=parser.parseFromString(
document.getElementById("txt").value,"text/xml");
meetingsNode = xmldoc.documentElement;
meetingNode = meetingsNode.firstChild;
console.log("meetingNode is:",meetingNode);
peopleNode = meetingNode.lastChild;
console.log("peoplenode is:",peopleNode);
//use console.log to figure out what the variable could be
console.log(xmldoc.getElementsByTagName("PEOPLE"));
//set a global variable named a to the what you want to inspect
//in the commandline you can type a. and after the dot the devtools
//will produce a list of attributes.
a = xmldoc.getElementsByTagName("PEOPLE");
personNode = xmldoc.getElementsByTagName("PEOPLE")
.item(0).lastElementChild;
a = personNode;
//in the commandline I can see a.lastChild is textnode
//the intellisense gives me an option lastElementChild
//didn't look it up but it could be Firefox specific
first_nameNode = personNode.lastElementChild;
last_nameNode = first_nameNode.nextSibling;
console.log("there are still some things to fix:",
meetingsNode, meetingNode, peopleNode,
first_nameNode, last_nameNode);
return;
outputText = "Third name: " +
first_nameNode.lastChild.nodeValue + ' '
+ last_nameNode.lastChild.nodeValue;
}
readXMLDocument();

javascript runtime error 0x800a1391

I'm learning a bit HMTL5 to prepare to the 70-480 exam. I'm trying to do some javascript code. It looks something like this:
function inchestometers(inches) {
if (inches < 0)
return -1;
else {
var meters = inches / 39.37;
return meters;
}
}
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
and I have such html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Htnl 5 test</title>
<script src="script/test.js"></script>
</head>
<body>
<p id="hello">Hello</p>
</body>
</html>
In my VS 2012 i have used the Asp.net Empty Web application project and added the Js file and also the html file. The problem is that The function runs properly without any exeptions. This function is taken from here: http://msdn.microsoft.com/en-us/library/cte3c772(v=vs.94).aspx
But whem I'm trying to run the code where I'm getting the document element it' crashint with the error like in the subject. What I've investigated is that the hello gets the null value. I've also tried the code thaken from here:
http://msdn.microsoft.com/en-us/library/yfc4b32c(v=vs.94).aspx - the example with the div. I have the same effect.
What is wrong? I know that there were simmilar subjects but I can't seem to find one matching to mine. Thank you kindly for your help.
Regards
Rafal
you are getting a problem because your javascript code is running before the element
<p id="hello">
is defined.
the simplest solution is to include your script at the end of the body section instead of in the head section but this would cause the document.write call to occur after the rest of the content.
another solution would be to place the code inside two functions like this
function do_conversion() {
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
}
function say_hello() {
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
}
then change the body section like this
<body onload='say_hello()'>
<script>
do_conversion();
</script>
<p id="hello">Hello</p>
</body>

Accessing inline CSS properties using getElementsByClassName

I have this piece of HTML code.
<div class="tagWrapper">
<i style="background-image: url(https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>
I need to get that url within the brackets. I tried using the getElementsByClassName() method but it didn't work. Since url is not a HTML element, I have no idea on how to take out the value. I can't use getElementById(), because I can't add an id to the HTML (it's not mine). It needs to work in Chrome and Firefox. Any suggestions?
You didn't add a jQuery tag, so here's a native solution (note that this likely won't work on older versions of IE, but you said it only has to work on Chrome and FF):
var origUrl = document.getElementsByClassName("tagWrapper")[0]
.children[0].style.backgroundImage;
var url = origUrl.substr(4, origUrl.length - 5);
Or
var url = origUrl.replace("url(", "").replace(")", "");
Here's a fiddle
EDIT
Answering your comment
document.getElementsByClassName("tagWrapper")
gets all elements with the class name tagWrapper. So to get the first one, you grab the zero index
document.getElementsByClassName("tagWrapper")[0]
Then you want the first child under there, and the backgroundImage property on this first child.
document.getElementsByClassName("tagWrapper")[0]
.children[0].style.backgroundImage;
From there it's a simple matter stripping the url( and ) from it
var url = origUrl.substr(4, origUrl.length - 5);
or
var url = origUrl.replace("url(", "").replace(")", "");
You can use querySelector():
Demo: http://jsfiddle.net/ThinkingStiff/gFy6R/
Script:
var url = document.querySelector( '.tagWrapper i' ).style.backgroundImage;
url = url.substr(4, url.length - 5);
If you where using jquery you could do something like this
$(".tagWrapper i").css("background-image")
I think if you use jQuery it will be easer.
var w = document.getElementsByClassName('tagWrapper')[0];
for (var i=0; i<w.childNodes.length; i++)
if (w.childNodes[i].tagName && w.childNodes[i].tagName.toLowerCase() == 'i')
return w.childNodes[i].style.backgroundImage;
<div class="tagWrapper">
<i id="something" style="background-image: url(https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>
// script / without jQuery
var url = document.getElementById('something').style.backgroundImage.match(/\((.*?)\)/)[1];
Use jQuery!!!
$("div.tagWrapper i").css("background-image").substr(4, $("div.tagWrapper i").css("background-image").length-5)
Example
If You don't have to care about Microsoft browsers, the raw JavaScript is quite easy. You can use getElementsByClassName and getElementsByTagName, however it is easier to try querySelectorAll. I've included both. The use of regular expression preserve relative links.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type='text/javascript'>
var do_find_a = function() {
var tmp = document.getElementsByClassName('tagWrapper')[0];
var tst = tmp.getElementsByTagName('i')[0].getAttribute('style');
return do_alert(tst);
}
var do_find_b = function() {
var tst = document.querySelectorAll('.tagWrapper i')[0].getAttribute('style');
return do_alert(tst);
}
var do_alert = function(tst) {
var reg = /background-image:\s*url\(["']?([^'"]*)["']?\);?/
var ret = reg.exec(tst);
alert (ret[1]);
return;
}
document.addEventListener('DOMContentLoaded',do_find_a,false);
document.addEventListener('DOMContentLoaded',do_find_b,false);
</script>
</head>
<body>
<div class='tagWrapper'>
<i style='background-image: url("http://example.com/image.jpg");'></i>
</div>
Text to ignore.
</body>
</html>
And jsFiddle version:
http://jsfiddle.net/hpgmr/

Categories

Resources