views:

197

answers:

2

How can I write this jQuery code in plain Javascript?

I can't use jQuery where this is going to be used.

$(function(){
$("td#dark[height='260']").append("<a href='http://www.website.com'&gt;&lt;/a&gt;");
});
+9  A: 

Try this:

var elem = document.getElementById("dark");  // #dark
if (elem && elem.nodeName == "TD" && elem.height == 260) {  // td#dark[height='260']
    var newElem = document.createElement("a");
    newElem.href = "http://www.example.com";
    elem.appendChild(newElem);
}

And for your non-standard document using the same ID on multiple elements:

var elems = document.getElementsByTagName("td");
for (var i=0; i<elems.length; i++) {
    var elem = elems[i];
    if (elem.id == "dark" && elem.height == 260) {  // td#dark[height='260']
        var newElem = document.createElement("a");
        newElem.href = "http://www.example.com";
        elem.appendChild(newElem);
    }
}
Gumbo
That's pretty much what I would've done. Make sure he notices the += too.
Kezzer
Thanks, but the problem is that the site is very non-standard, and uses several ID dark on both td and table tags. Any ideas on how I can make it work?
mofle
also, since you can't wrap a startup function in $(), make sure to set an onload so your DOM is loaded first
cobbal
-1 never use “innerHTML+=”. This serialises and re-parses the contents of the td, losing any JavaScript properties such as event handlers, listeners and objects with a reference to nodes inside it.
bobince
bobince: What should I use instead?
mofle
Christoph
@Christoph: You’re right. I just copied the code from the first example and didn’t adjust it.
Gumbo
Where's the check for id "dark"?
Crescent Fresh
Oops, accidentally deleted it. :)
Gumbo
@mofle: you can set innerHTML on a throwaway <div> then appendChild each child of the div to the place you want it. Of course in this case it's such a small amount of markup that it's easier to just createElement it, as Gumbo is doing now.
bobince
A: 

but the problem is that the site is very non-standard, and uses several ID dark on both td and table tags. Any ideas on how I can make it work? – mofle

You will need to loop through each HTML element within the body (xpath would be ideal), get the tag, see if its td and if so, read the height element and see if it equals 260. This is because .getElementById will only return one result as only one ID should be present, but as you say, the website is non-standard.

Gary Green