Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

insertBefore broken in Firefox? 1

Status
Not open for further replies.

phaedrus28

Programmer
Mar 9, 2007
1
CA
Hi,

I'm trying to code a sortable list using links on each list item, and I'm using the DOM to shift the items around. The code below illustrates the problem I'm experiencing - in IE 6/7 insertBefore works fine, but in Firefox insertBefore doesn't work unless you click a given link several times.

I would have expected Firefox to update the display straight away - appendChild works fine, but I need insertBefore to work.

Does anyone know if there is a workaround for this?

<html>

<head>

<script language="javascript">
function test(li) {
var e = document.getElementById('li' + li);
var ol = document.getElementById('list');
var s = e.previousSibling;
ol.removeChild(e);
ol.insertBefore(e, s);
}
</script>
</head>

<body>

<ol id="list">
<li id="li1">One <a href="#" onclick="test(1);">1</a></li>
<li id="li2">Two <a href="#" onclick="test(2);">2</a></li>
<li id="li3">Three <a href="#" onclick="test(3);">3</a></li>
<li id="li4">Four <a href="#" onclick="test(4);">4</a></li>
</ol>

</body>

</html>
 
If you alert s.nodeType when s is not nothing, you will discover that moz capture the text node (nodeType=3) rather than element node (nodeType=1). Also that when li is the first, you have to contain the error of s being nothing rightaway in ie or eventually in ff. Hence, to overcome this difference of detail in the implementation of previousSibling, do this for ie/moz cross-browser error free.
[tt]
function test(li) {
var e = document.getElementById('li' + li);
var ol = document.getElementById('list');
var s=e.previousSibling;
while(s && s.nodeType && s.nodeType!=1 && s.previousSibling) {
s=s.previousSibling;
}
if (s && s.nodeType && s.nodeType==1) {
ol.removeChild(e);
ol.insertBefore(e, s);
} //else do nothing (such as li=1)
}
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top