PDA

View Full Version : Finding the background with JS


itsjareds
07-05-2008, 12:47 AM
Hi, i need to write a script that finds the background image of a table column (<td>).

This is the script I currently have:

var background = document.getElementsByTagName('table')[1].background.src;


..and this is the HTML that I am trying to change:

<body>
<table>
<tr>
<td>
<table background="this is what i want.jpg">


When I run the script, the error console says:
document.getElementsByTagName("table")[1].background is undefined

Does anyone know why this doesn't work?

_Aerospace_Eng_
07-05-2008, 01:21 AM
Try
var background1 = document.getElementsByTagName('table')[1].background;
Also make sure the table has been loaded before you try to access it.

itsjareds
07-05-2008, 01:53 AM
now it doesn't say anything in the error console, and when i put background1 in <img src="' + background1 + '">, it doesn't show anything.

rangana
07-05-2008, 03:34 AM
The reason is because table don't have a background attribute (http://www.w3schools.com/tags/tag_table.asp).

The fix is by changing your markups:

<table style="background-image:url('this is what i want.jpg')">


And your script to:

var background = document.getElementsByTagName('table')[1].style.backgroundImage;
alert(background.split('url')[1]);


Hope it helps.

itsjareds
07-05-2008, 05:42 AM
I figured that.

I can't change the markup because it's not my site. I'm editing it through Greasemonkey (firefox addon), so all I can do is use the elements they already have.

Either way, I found a workaround that works alright. The strange thing was the background really did work. It showed up :confused: