Monday, January 26, 2009

how to get the styles from a parent window in javascript

Hi,

Recently i had a scenario, which i had to load a page in a iframe, it was working fine, but the problem was the styles was not setting up in the child window, i cannot hard code the styles as the style sheets will be generated dynamically and i will be able to get the styles, i tried to find out a way, did some googling and found the way in javascript.
call the javascript function in child window onload, it will take care of the rest

function setParentStyle()
{
if(window.top && window.top.location.href != document.location.href)
{
// all parent's <link> tag's
var linkrels = window.top.document.getElementsByTagName('link');
// my head - child window head tag
var small_head = document.getElementsByTagName('head').item(0);
// loop through parent's links
for (var i = 0, max = linkrels.length; i < max; i++)
{
// are they stylesheets
if (linkrels[i].rel && linkrels[i].rel == 'stylesheet')
{
// create new element and copy all attributes
var thestyle = document.createElement('link');
var attrib = linkrels[i].attributes;
for (var j = 0, attribmax = attrib.length; j < attribmax; j++)
{
thestyle.setAttribute(attrib[j].nodeName, attrib[j].nodeValue);
}
// add the newly created element to the head
small_head.appendChild(thestyle);

}
}
}
}

i am just copying and pasting it what i got, there is nothing which i did on my own :) :)

Thanks
Venkat