0

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'></a>");
});
3
  • 1
    And this is why I have a problem with jQuery... Commented Mar 20, 2009 at 8:38
  • Huh? Because it's so simple and its filters are so powerful? Commented Mar 20, 2009 at 9:57
  • 1
    I assume this is because you have more than one element with the id of 'dark'... This is very, very bad. If you fix that then you can simply use document.getElementById('dark') and use the built-in dom methods (appendChild, etc). Commented Mar 20, 2009 at 15:14

2 Answers 2

10

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);
    }
}
Sign up to request clarification or add additional context in comments.

10 Comments

That's pretty much what I would've done. Make sure he notices the += too.
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?
also, since you can't wrap a startup function in $(), make sure to set an onload so your DOM is loaded first
-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: What should I use instead?
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.