[thelist] DOM: previousSibling and LI tags

Christian Heilmann codepo8 at gmail.com
Thu Jan 19 11:45:57 CST 2006


> Hi,
>
> I'm having an issue where i want to access the previous list item
> using javascript.
>
> this.previousSibling works in Explorer, but in firefox it returns the
> text element,
>
> so if i use this.previousSibling.previousSibling it will work
> correctly in firefox but not IE.
>
> Quite a pain, how do others get around this issue? are we back to
> browser sniffing :(

No, just understanding the DOM and safely use it. Test the type of the
node and apply your bits and bobs then. You can use this replacement
function for example to really reach the previous LI.

function realPreviousSibling(node){
  var tempNode=node.previousSibling;
  while(tempNode.nodeType!=1){
    tempNode=tempNode.previousSibling;
  }
  return tempNode;
}

realPreviousSibling(this) will now return the first previous element
sibling, regardless of browser.

HTH
Chris

--
Chris Heilmann
Blog: http://www.wait-till-i.com
Writing: http://icant.co.uk/
Binaries: http://www.onlinetools.org/



More information about the thelist mailing list