Monday, April 25, 2011

jQuery code in plain Javascript

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>");
});
From stackoverflow
  • 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);
        }
    }
    
    Kezzer : That's pretty much what I would've done. Make sure he notices the += too.
    mofle : 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?
    cobbal : also, since you can't wrap a startup function in $(), make sure to set an onload so your DOM is loaded first
    bobince : -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.
    mofle : bobince: What should I use instead?
    Christoph : @Gumbo: I'd drop the check for `elem && elem.nodeName == "TD"` in the second version - they're redundant because you used `getElementsByTagName()`
    Gumbo : @Christoph: You’re right. I just copied the code from the first example and didn’t adjust it.
    Crescent Fresh : Where's the check for id "dark"?
    Gumbo : Oops, accidentally deleted it. :)
    bobince : @mofle: you can set innerHTML on a throwaway
    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.
  • 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.

0 comments:

Post a Comment