...

View Full Version : Correct placement of code using insertBefore/After



wtmh
08-20-2010, 07:21 PM
I'm brand new to JavaScript, and I come from a purely logical scripting background so forgive me if this is the most poorly formed code/bad technique that you've recently seen.

I've played the google games for days and I surrender. I usually find a way to fight through it and figure it out, but I'm going to have to cede this one.

I'm simply trying to put a new tab next to a tab that is already present on a page (classed: mirrortab_first)

I'm trying to use XPath to select the element and then place newTab before it.

Seemed simple enough to start. But as the code sits, the tab always winds up at the bottom of the page.

Any thoughts?

Kind regards.



var newTab = document.createElement("div");
newTab.setAttribute('id','newTab');

newTab.innerHTML =
'<table cellpadding="0" cellspacing="0" border="0"><tbody><tr>' +
'<td class="mirrortab_first">&nbsp;</td>' +
'<td class="mirrortab_back">' +
'<a style="cursor:pointer;">Hide Classifieds</a>' +
'</td>' +
'<td class="mirrortab_last">&nbsp;</td>' +
'</tr></tbody></table></div>';


var tabLocation = document.evaluate('//td[contains(@class, "mirrortab_first")][1]',document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);
for (i=0; i<tabLocation.snapshotLength; i++)
{
tL = tabLocation.snapshotItem(i).parentNode;
}

document.body.insertBefore(newTab, document.tL);

Old Pedant
08-20-2010, 08:38 PM
Ummm...document.evaluate() is *NOT* supported in all browser, at all. Certainly not in MSIE.

But in any case, you areo doing

document.body.insertBefore(newTab, document.tL);

but tL is a simple variable, not a member of document. So presumably document.tL is null and so the placement you are getting is expected.

Did you try simply using

document.body.insertBefore(newTab, tL);
???

But also maybe you should find a way to do this that doesn't depend on evaluate( ).

If you showed us the web page, it would be easier to help.

wtmh
08-20-2010, 09:56 PM
I have tried
document.body.insertBefore(newTab, tL);

Which results in the tab not showing at all.

I don't have a finished page since I'm just doing this on a blank throw away document just to see if I can do it. Again, I'm learning.

What ways would I be able to trace a complex path to an element without using evaluate? I'm all about compatibility. :P

Old Pedant
08-20-2010, 10:18 PM
Well, the easiest thing to do would be to put a class name on each of your tabs.

And then just use getElementsByClassName() and insert the new div before/after the one you are after. It's possible, of course, to look inside the tabs for the <td> with that class, but just slower and more of a pain.

On really old browsers, getElementsByClassName doesn't exist, but it's easy to write it using getElementsByTagName and then inspecting each element found for the desired class.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum