Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Coffee Mugshot
Jun 26, 2010

by Lowtax

Lumpy posted:

code:
eventList.innerHTML =ajax.responseText.split("\n");
You were trying to set the innerHTML of a DOM node to an Array object.

All the examples I looked at for using XMLhttpRequest used a variation of this, my original code actually split the original string into an array and read every single element into the innerHTML one at a time after some parsing. I mean, they used different .split() parameters. I guess I forgot to mention that this code never executed anyways. ajax.status was always 0, never 200, so it never reached that inner branch of code. If I'm understanding the w3.org reference for XMLhttpRequest, status 0 means file not found.

Because of this, I thought, "oh maybe the url needs a more explicit address to find the file I'm looking for instead of a relative address like 'events.txt'."

So, I also tried variations such as: "file://C:/blah/events.txt" and "C:/blah/events.txt" or, if the javascript strings were having an issue trying to figure which characters are escape characters, I also tried: "file:\/\/C:\/blah\/events.txt" and other variations, but I never got ajax.status to leave the 0 status. I'm still not entirely sure what I'm doing wrong, and the responses I found via google kind of had me wondering if this was even possible.

Adbot
ADBOT LOVES YOU

OddObserver
Apr 3, 2009
.status won't work outside http/https, being the http status code. And, really, XHR over file:/// isn't guaranteed to work, either.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

OddObserver posted:

That actually works in general, due to Array.prototype.toString

So we should always assume we can use an array like a string?

OddObserver
Apr 3, 2009

Lumpy posted:

So we should always assume we can use an array like a string?

I can't be anywhere that definitive; never thought it out. Except, well, in most contexts where it matters it will indeed auto-coerce into a string value (not to be confused with a string object, of course), e.g.: A = ["A", "B"]; A + "C"; produces "A,BC". And, well, most DOM methods will likely use the ToString operator as well, but those things always have wacko special cases.

JS might not be quite as sane as you might think. (See also valueOf).

And, well, obviously, stuff like index properties --- which aren't standard in 3rd edition anyway, dunno about 5th --- wouldn't use the string coercion, and neither would for .. in and the like.

See also auto-stringifying Selection object or whatever that was.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

OddObserver posted:

I can't be anywhere that definitive; never thought it out. Except, well, in most contexts where it matters it will indeed auto-coerce into a string value (not to be confused with a string object, of course), e.g.: A = ["A", "B"]; A + "C"; produces "A,BC". And, well, most DOM methods will likely use the ToString operator as well, but those things always have wacko special cases.

JS might not be quite as sane as you might think. (See also valueOf).

And, well, obviously, stuff like index properties --- which aren't standard in 3rd edition anyway, dunno about 5th --- wouldn't use the string coercion, and neither would for .. in and the like.

See also auto-stringifying Selection object or whatever that was.

That was kind of my point. Telling beginners / people who are new to the language that assigning an Array literal where you want a string version of it as "generally OK thing" to do may not be in their best interests.

Coffee Mugshot
Jun 26, 2010

by Lowtax

OddObserver posted:

.status won't work outside http/https, being the http status code. And, really, XHR over file:/// isn't guaranteed to work, either.

Now I'm really lost, if neither of those work all the time, was it just impossible for me to do it this way?

Lumpy posted:

That was kind of my point. Telling beginners / people who are new to the language that assigning an Array literal where you want a string version of it as "generally OK thing" to do may not be in their best interests.

I thought the same thing at first, until I couldn't get it to work. I have a C/C++ background, so I really didn't believe that assigning a string array to a location where I want a string to be read would work, either. Eventually, after not getting anywhere for a while, I decided that maybe I should just straight-up copy and paste what other people were saying worked.

Anyways, thanks for the tips guys, some of this stuff went over my head when I was writing originally, but now I understand what the code was supposed to do. I'm still not entirely understanding what I should change if I wanted to it work in this case, though.

OddObserver
Apr 3, 2009

Rainbow Pony Deluxe posted:

Now I'm really lost, if neither of those work all the time, was it just impossible for me to do it this way?
Well, it's perfectly fine for http (keeping to the same domain). file:/// is just messier because:
1) XMLHttpRequest is meant for, well, http, so it does a lot of things that don't really make sense for local files (status could be faked as 200/403/404, but what about stuff that has to do with http headers?). I think you can probably get away with just checking readyState, though.

2) There are various security considerations involving file:/// that if I am not mistaken (I might be on this) tend to be handled differently between browsers. Probably not such a big deal when just prototyping, though, and of course production stuff will likely just use http anyway, won't it?

Rainbow Pony Deluxe posted:

I thought the same thing at first, until I couldn't get it to work. I have a C/C++ background, so I really didn't believe that assigning a string array to a location where I want a string to be read would work, either. Eventually, after not getting anywhere for a while, I decided that maybe I should just straight-up copy and paste what other people were saying worked.
JavaScript is basically providing an analogue of an "operator const char*()" --- an implicit conversion from an array to string. Actually, I was quite surprised it worked too, didn't know one was provided. Of course, if one wasn't, you would likely end up with "[object Array]" as your string.

Edit: might be worth picking at the JS error console or such to make sure there are no security warnings or the like.

OddObserver fucked around with this message at 22:04 on Aug 10, 2010

horse_ebookmarklet
Oct 6, 2003

can I play too?
AJAX question!
I am running into race conditions due to everything being asynchronous. How can I ensure I have my data before proceeding?
The following is my scenario!
code:
function ReadableFileFactory() {
	this.getReadableFile = function(path) {
		file = new ReadableFile();
		responseWritten = false;
		new Ajax.Request(path, {
			method: "post",
			onCreate: function(request) {
				request.transport.overrideMimeType('text/plain; charset=x-user-defined');
			},
			onSuccess: function(response) {
				file.setData(response.responseText);
			}
		});
		//file is being returned and acted on before the onSuccess of Ajax.Request is called
		return file;
	}
}
I could have getReadableFile accept a callback and pass my result to that... But I feel a little silly having to create a callback just to simply return an object. This gets super messy once I start needing to read multiple files. I'll have to write something to observe all of my file callbacks and run another callback when they are all executed.
This is turning into a gigantic mess very quickly just to ensure I have an object. Am I just approaching this from the wrong way? Is the callback-observer that I described the proper way to do things in javascript?

epswing
Nov 4, 2003

Soiled Meat

NotHet posted:

Is the callback-observer that I described the proper way to do things in javascript?

I think so, yeah.

You have to wait until you receive the contents of the file before proceeding anyways, right? So you can't do anything until onSuccess is called. So give onSuccess something to do after file.setData (execute the callback you describe).

If there's another way to accomplish this, I'm all ears.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

NotHet posted:

AJAX question!
I am running into race conditions due to everything being asynchronous. How can I ensure I have my data before proceeding?
The following is my scenario!
code:
function ReadableFileFactory() {
	this.getReadableFile = function(path) {
		file = new ReadableFile();
		responseWritten = false;
		new Ajax.Request(path, {
			method: "post",
			onCreate: function(request) {
				request.transport.overrideMimeType('text/plain; charset=x-user-defined');
			},
			onSuccess: function(response) {
				file.setData(response.responseText);
			}
		});
		//file is being returned and acted on before the onSuccess of Ajax.Request is called
		return file;
	}
}
I could have getReadableFile accept a callback and pass my result to that... But I feel a little silly having to create a callback just to simply return an object. This gets super messy once I start needing to read multiple files. I'll have to write something to observe all of my file callbacks and run another callback when they are all executed.
This is turning into a gigantic mess very quickly just to ensure I have an object. Am I just approaching this from the wrong way? Is the callback-observer that I described the proper way to do things in javascript?

If you are just going to be spinning your wheels until you get your data, you might as well use a synchronous query (I'm using jQuery here because it's easy):

code:
file = new ReadableFile();
var data = jQuery.ajax({
  url: "someScript.php",
  async: false // <--- ooooh!
 }).responseText;
file.setData( data );

epswing
Nov 4, 2003

Soiled Meat
But that will lock up the UI for as long as it takes to fetch the file, which could be half a second, but could also be two or three.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

epswing posted:

But that will lock up the UI for as long as it takes to fetch the file, which could be half a second, but could also be two or three.

Yeah, so you show a "Loading data!" thing... I guess was assuming that locking the UI wasn't an issue because nothing could / should happen until data was loaded. Apparently, I assumed wrong!

horse_ebookmarklet
Oct 6, 2003

can I play too?
I'm writing for a WebOS. Palm doesn't want you using synced queries in the first place otherwise I'd have done that right away. The problem with synced queries and the spinning wheel method is the entire device will lock up as it all runs in webkit.

I'm just going to keep track of what callbacks have been called and once I hit the magic number fire off my final callback.

Thanks for the advice

Gentle Marmot
Mar 25, 2005
like the sugar
Im trying to write a simple HTML page with javascript that can parse through a local XML file using XMLHttpRequest and populate some fields in my page with data from the XML file. Google Chrome throws "Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101", IE tells me access denied at my open function call, and firefox tells me nothing is wrong but doesnt do anything.

Here is my page
code:
<html>
<head>
<title>Test Html file</title>
<script type ="text/javascript">
function loadXMLDoc() {

    var request = new XMLHttpRequest();
    request.onreadystatechange=function() {
        if (request.readyState == 4 && request.status == 200) {
            xmlDoc = request.responseXML;
            x=xmlDoc.getElementsByTagName("ARTIST");
            document.getElementById(value_1).innerHTML = x[0].childNodes[0].nodeValue;
            document.getElementById(value_2).innerHTML = x[1].childNodes[0].nodeValue;
            document.getElementById(value_3).innerHTML = x[2].childNodes[0].nodeValue;
            document.getElementById(value_4).innerHTML = x[3].childNodes[0].nodeValue;
            document.getElementById(value_5).innerHTML = x[4].childNodes[0].nodeValue;
        }
    }
    request.open("GET","values.xml", true);
    request.send();
}

</script>
</head>
<body>
<form name = "where">
 <table>
  <tr><td><b>Here's a list that should populate</b></td></tr>
  <tr>
   <td>Value 1: </td>
   <td><span class = "values" id = "value_1"></span></td>
  </tr>
  <tr>
   <td>Value 2: </td>
   <td><span class = "values" id = "value_2"></span></td>
  </tr>
  <tr>
   <td>Value 3: </td>
   <td><span class = "values" id = "value_3"></span></td>
  </tr>
  <tr>
   <td>Value 4: </td>
   <td><span class = "values" id = "value_4"></span></td>
  </tr>
  <tr>
   <td>Value 5: </td>
   <td><span class = "values" id = "value_5"></span></td>
  </tr>
  <tr><td><input type = "button" value = "Click Me" onclick =
"loadXMLDoc();"</td></tr>
 </table>
</form>
</body>
</html>
and here is the xml file, saved as values.xml locally.

Any ideas what the problem might be?

Gentle Marmot fucked around with this message at 23:52 on Aug 11, 2010

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Gentle Marmot posted:



and here is the xml file, saved as values.xml locally.

Any ideas what the problem might be?

1. Are you serving up the page via a web server, or file:/// url?

2. Why aren't you using jQuery? It makes life so much easier.

Gentle Marmot
Mar 25, 2005
like the sugar

Lumpy posted:

1. Are you serving up the page via a web server, or file:/// url?

Im using file:// I dont have a webserver to try this on right now. I have a linux box to gently caress around with this stuff on but im elsewhere on windows and I dont want to bother getting ruby and webrick going on here right now. Basically all I care about is getting information into a JavaScript file out of a locally stored XML file.

quote:

2. Why aren't you using jQuery? It makes life so much easier.

This doesnt seem like it would particularly be a hard problem and I want to learn how XHR works before using a library. Also how much code could I really save doing this same problem with jquery, ive barely written any as it is.

Edit: Jquery does look pretty sweet actually and im gonna mess around with that but I still want to know why this isnt working.

Gentle Marmot fucked around with this message at 02:13 on Aug 12, 2010

Supervillin
Feb 6, 2005

Pillbug
file:/// requests have status 0, not 200. HTTP status codes are written by the HTTP server, so if there is no server, there's no code.

If you decide to go the jQuery route, cool, otherwise modify your status check:
code:
if (request.readyState == 4 && (request.status == 200 || request.status === 0)) ...

Gentle Marmot
Mar 25, 2005
like the sugar
Sweet it works... in firefox. IE and google chrome still send the same errors but some searching around seems like chrome broke being able to look at local XMLs like this and I dont care about IE.

Oh well, when I get back to my linux box ill host something and mess with it there and Im gonna take a look into jQuery.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Gentle Marmot posted:

Sweet it works... in firefox. IE and google chrome still send the same errors but some searching around seems like chrome broke being able to look at local XMLs like this and I dont care about IE.

Oh well, when I get back to my linux box ill host something and mess with it there and Im gonna take a look into jQuery.

As Supervillin said, "stuff" is different when not served via http. Chrome actually decided to follow the correct way of doing things with file:/// URLs ( no cookies, etc. ) that "broke" many a thing that had been done using the up until that point "incorrect but everyone did it" way.

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

Testing ajax over file:/// is a bitch. I just set up lightttpd and point my browser to localhost when I want to do that stuff. It's ridiculously easy to setup on linux:
1 apt-get install it
2 set permissions on /var/www so that you can edit it
3 put your files in there
4 point your browser to http://localhost/blah

OddObserver
Apr 3, 2009

Lumpy posted:

As Supervillin said, "stuff" is different when not served via http. Chrome actually decided to follow the correct way of doing things with file:/// URLs ( no cookies, etc. ) that "broke" many a thing that had been done using the up until that point "incorrect but everyone did it" way.

There are also security considerations involved. For example if a browser permits reading of absolute file:/// URLs, and not just things in the same directory, if a user is tricked to open a local/untrusted html file in that browser, it appears quite possible to do things like steal their cookies and ship them over the network to some outside host.

Coffee Mugshot
Jun 26, 2010

by Lowtax

Gentle Marmot posted:

Sweet it works... in firefox. IE and google chrome still send the same errors but some searching around seems like chrome broke being able to look at local XMLs like this and I dont care about IE.

Oh well, when I get back to my linux box ill host something and mess with it there and Im gonna take a look into jQuery.

I'm not sure what the issue is in IE, but as far as I know, Chrome won't let you load local files with ajax (using jQuery or not) unless you open it with either "--allow-file-access-from-files" or "--disable-web-security". At least that's how I got it to work without having a web-server up.

Also, for IE, depending on which version it is, don't you want to make a "new ActiveXObject("Microsoft.XMLHTTP");" instead of an XMLhttpRequest? Although, I think IE7 supports this, so I don't know what the issue is.

skipdogg
Nov 29, 2004
Resident SRT-4 Expert

I'm creating a .pac file for our computers here at work, and we're rolling out a new proxy appliance that has an issue with a certain tool our agents use and I'm getting stuck trying to work around this.

I'm pretty sure whats happening is the site I'm trying to work around meets several of my if statements. How does one go about telling it to stop processing after an if condition is true. I know this is basic, but I have no idea about javascript or coding in general, and have only got this far learning as I go from sparse info about .pac files on google

So basically the if statements in the .pac are laid out like so (this is a very truncated version)

code:

function FindProxyForURL(url, host)
    {

if(
dnsDomainIs(host, "stupidsite.com")) {return old_proxy;}

if(
shExpMatch (url, "https://*.*.*.*") ||
shExpMatch (url, "https://*.*.*.*"))  
{return old_proxy;}

if(

isInNet(resolved_ip, "x.x.0.0", "255.255.0.0") ||  

(repeated about 40 times for 40 different subnets)
isInNet(resolved_ip, "x.x.0.0", "255.255.0.0"))
    {return no_proxy;}

{return new_proxy;}

}

I'm assuming the problem I have is the stupidsite.com URL also is a true condition for one of the isInNet statements as well. My question is, how can I make it so if the first or second if statements (dnsDomainIs or shExpMatch) it doesn't continue on to process all of the isInNet statements.

I'm guessing I might have to put some if / else if / else in there, but I'm at a loss to be honest.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

skipdogg posted:

I'm creating a .pac file for our computers here at work, and we're rolling out a new proxy appliance that has an issue with a certain tool our agents use and I'm getting stuck trying to work around this.

I'm pretty sure whats happening is the site I'm trying to work around meets several of my if statements. How does one go about telling it to stop processing after an if condition is true. I know this is basic, but I have no idea about javascript or coding in general, and have only got this far learning as I go from sparse info about .pac files on google

So basically the if statements in the .pac are laid out like so (this is a very truncated version)

code:

function FindProxyForURL(url, host)
    {

if(
dnsDomainIs(host, "stupidsite.com")) {return old_proxy;}

if(
shExpMatch (url, "https://*.*.*.*") ||
shExpMatch (url, "https://*.*.*.*"))  
{return old_proxy;}

if(

isInNet(resolved_ip, "x.x.0.0", "255.255.0.0") ||  

(repeated about 40 times for 40 different subnets)
isInNet(resolved_ip, "x.x.0.0", "255.255.0.0"))
    {return no_proxy;}

{return new_proxy;}

}

I'm assuming the problem I have is the stupidsite.com URL also is a true condition for one of the isInNet statements as well. My question is, how can I make it so if the first or second if statements (dnsDomainIs or shExpMatch) it doesn't continue on to process all of the isInNet statements.

I'm guessing I might have to put some if / else if / else in there, but I'm at a loss to be honest.

Your code *should* work, since there is a return in every IF.

At least I think there is, but your crazy formatting makes it hard to tell.

The following behaves as expected: 'a' is matched, and the function returns, so the 'b' if statement doesn't run.

code:
var a = 2;
var b = 3;
function pie(){
 if( a == 2 ) {
   alert("hooray");
   return;
 }
 if( b == 3 ) {
   alert( "you won't see this" );
 }
}

pie();
EDIT: try formatting your code the Crockford Way(tm) and see if it works: you could be causing silent errors.

Lumpy fucked around with this message at 23:59 on Aug 12, 2010

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
innerText in IE returns the text of an element without HTML tags or newlines.

textContent in Firefox returns the text of an element without HTML tags, but maintaining newlines.

I want textContent's style in an innerText browser. Is there any easy way of doing this? I'm basically using these to scrub input into a chat app to get rid of any HTML tags that have been entered, but I also want to keep whitespace, which means innerText is not going to cut it. I'm willing to abandon textContent if it means getting this all working in IE as well. Any ideas?

KuruMonkey
Jul 23, 2004

Golbez posted:

Any ideas?

My knee-jerk reaction was "use jQuery: $('#id).text()"

But I would have looked oh so very dumb:

quote:

(Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.)
http://api.jquery.com/text/

So, my second knee-jerk reaction is that if it were doable, jQuery would probably have done it.

So...
maybe "use jQuery: $('#id').html()" and then scrub the html out yourself?
But:

quote:

Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.
http://api.jquery.com/html/

Might be less of a problem?

Alternately this might be of use: http://eligrey.com/blog/post/textcontent-in-ie8
(i.e 8 only?)

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

KuruMonkey posted:

My knee-jerk reaction was "use jQuery: $('#id).text()"

But I would have looked oh so very dumb:

http://api.jquery.com/text/

So, my second knee-jerk reaction is that if it were doable, jQuery would probably have done it.

So...
maybe "use jQuery: $('#id').html()" and then scrub the html out yourself?
But:

http://api.jquery.com/html/

Might be less of a problem?

Alternately this might be of use: http://eligrey.com/blog/post/textcontent-in-ie8
(i.e 8 only?)

I did try .text(), and it does indeed produce different results in different browsers, exactly the same as if I had used textContent and innerHTML. I also tried a loop using node.data (seen here) but got the same results.

You have a point about jQuery; for all they talk about pure browser compatibility, it does seem notable that they would be specific about that command not being universal. So this is harder than it seems. Good job, Microsoft.

As for scrubbing the HTML myself, that sounds difficult, know any libraries/jQ plugins for it? :) I mean, I guess, worst-case, I could either live with the whitespace issue, or just make HTML safe (html entities) for IE browsers and clean it in FF. This would be simple if it were being passed to PHP, but this is a chat app so it needs to display what they just typed in, and I've noticed that means executing any HTML they put in as well. (Found that out while copying and pasting some random webpage and it tried to download a new javascript file)

As for the last link you posted, the link to his js file brings back a 404. And it's minified, so even if it was there it'd be difficult to see what makes it work. :(

KuruMonkey
Jul 23, 2004
TBH at this point all I can do is google "jquery strip html" - which I shall leave as an exercise for the reader :)

For the comedy option, of course...

You could write a simple HTML stripping service in PHP and call it from JS :v:

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

KuruMonkey posted:

TBH at this point all I can do is google "jquery strip html" - which I shall leave as an exercise for the reader :)

For the comedy option, of course...

You could write a simple HTML stripping service in PHP and call it from JS :v:

But then there'd be a noticeable delay between them hitting enter and their own text appearing on the screen. :)

Piell
Sep 3, 2006

Grey Worm's Ken doll-like groin throbbed with the anticipatory pleasure that only a slightly warm and moist piece of lemoncake could offer


Young Orc
I am putting together a website for a library, and they are going to be adding a pdf document to a page every so often. I want to have some javascript to find all the files in a subfolder and build links to them in a table whenever you go to the page, so that it automatically picks up the new documents without having to manually update the page every time you go to it. How would this be done?

Sergeant Rock
Apr 28, 2002

"... call the expert at kissing and stuff..."
You'd need to do it back-end. Javascript can't read from the file system, for security reasons.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Sergeant Rock posted:

You'd need to do it back-end. Javascript can't read from the file system, for security reasons.

You could do it in JS if you have directory indexes turned on (not a good idea), but it would be pretty bad indeed.

Mackerel, the Thief
Sep 24, 2003

Piell posted:

I am putting together a website for a library, and they are going to be adding a pdf document to a page every so often. I want to have some javascript to find all the files in a subfolder and build links to them in a table whenever you go to the page, so that it automatically picks up the new documents without having to manually update the page every time you go to it. How would this be done?

Define "every so often." If it's once every couple of days, is it really that big of a deal to do it by hand?

Mackerel, the Thief
Sep 24, 2003

Golbez posted:

innerText in IE returns the text of an element without HTML tags or newlines.

textContent in Firefox returns the text of an element without HTML tags, but maintaining newlines.

I want textContent's style in an innerText browser. Is there any easy way of doing this? I'm basically using these to scrub input into a chat app to get rid of any HTML tags that have been entered, but I also want to keep whitespace, which means innerText is not going to cut it. I'm willing to abandon textContent if it means getting this all working in IE as well. Any ideas?

Magic:

code:
        var regExp = /<(.|\n)*?>/g,
            string = "<div class='boners'>My text in here</div>";
        string.replace(regExp, "");

zorch
Nov 28, 2006

Is there a way that I can replace one element with another? I'm writing a greasemonkey script and am trying to replace td elements with divs. I also need to preserve the class / ID attributes.

Mackerel, the Thief
Sep 24, 2003

emoltra posted:

Is there a way that I can replace one element with another? I'm writing a greasemonkey script and am trying to replace td elements with divs. I also need to preserve the class / ID attributes.

code:
    <script type="text/javascript">
        var tds = document.getElementsByTagName('td');
        for (i = 0; i < tds.length; ++i) {
            newElement = document.createElement('div');
            tds[i].parentNode.insertBefore(newElement, tds[i]);
            newElement.innerHTML = tds[i].innerHTML;
            newElement.setAttribute('id', tds[i].getAttribute('id'));
            newElement.setAttribute('class', tds[i].getAttribute('class'));
            tds[i].parentNode.removeChild(tds[i]);
        }
    </script>
The only thing here is that you'd also have to remove <tr> and <table> tags as well or you might have some unexpected behavior / unwanted styling going on.

zorch
Nov 28, 2006

Mackerel, the Thief posted:

code:
    <script type="text/javascript">
        var tds = document.getElementsByTagName('td');
        for (i = 0; i < tds.length; ++i) {
            newElement = document.createElement('div');
            tds[i].parentNode.insertBefore(newElement, tds[i]);
            newElement.innerHTML = tds[i].innerHTML;
            newElement.setAttribute('id', tds[i].getAttribute('id'));
            newElement.setAttribute('class', tds[i].getAttribute('class'));
            tds[i].parentNode.removeChild(tds[i]);
        }
    </script>
The only thing here is that you'd also have to remove <tr> and <table> tags as well or you might have some unexpected behavior / unwanted styling going on.

Yeah, I just needed to ask about replacing the elements because it seems like all of the replacement tutorials completely replace the inner content.

Thanks a bunch!

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

emoltra posted:

Is there a way that I can replace one element with another? I'm writing a greasemonkey script and am trying to replace td elements with divs. I also need to preserve the class / ID attributes.

Uses jQuery, but does what you want, and gets all attributes:
code:
jQuery('td').each( function(){
  var i;
  var me = jQuery(this);
  var myAttrs = this.attributes;
  var newEl = jQuery('<div />');
  for( i = 0; i < myAttrs.length; i += 1 ){
    newEl.attr( myAttrs[i].name , myAttrs[i].value );
  }
  newEl.html( me.html() );
  me.replaceWith( newEl );
});

Mackerel, the Thief
Sep 24, 2003

Lumpy posted:

jQuery

Brevity version:

code:
$('td').each(function() {
    for (i = 0, attrs = "", attrLength = this.attributes.length; i < attrLength; ++i)
        attrs += ' ' + this.attributes[i].name + '="' + this.attributes[i].value + '"';
    $(this).replaceWith( $("<div"+attrs+">"+$(this).html()+"</div>") );
});

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Mackerel, the Thief posted:

Brevity version:

code:
$('td').each(function() {
    for (i = 0, attrs = "", attrLength = this.attributes.length; i < attrLength; ++i)
        attrs += ' ' + this.attributes[i].name + '="' + this.attributes[i].value + '"';
    $(this).replaceWith( $("<div"+attrs+">"+$(this).html()+"</div>") );
});

You have a couple variable names to cut down one letter mister. He might be able to understand those parts.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply