getElementsByTagName only get top level tags?
i have this really weired js problem.
in summary, i get a element not found if i use (document.getElementsByTagName("p"))[0]
and if the p
tag is inside a div
like this
<div id="main">
<p>see</p>
</div>
but as soon as i remove the div wrapper, all things work.
after 30 min, i've reduced the problem to this simple code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>ttttttttttttttttttttt</title>
</head>
<body>
<div id="main">
<p>see</p>
</div>
<script type="text/javascript">
var myobj = document.createElement("div");
myobj.innerHTML='yesyes';
document.body.insertBefore(myobj, (document.getElementsByTagName("p"))[0] );
</script>
</body>
</html>
put above in a file. Open in Firefox or Chrome or IE8. If successful, you should see “yesyes”.
If开发者_Python百科 you remove the <div id="main">
wrapper, then it works.
it seems there something i'm not understanding about getElementsByTagName
??
Nothing to do with getElementsByTagName
, everything to do with insertBefore
. Try this:
document.getElementById('main').insertBefore(myobj, (document.getElementsByTagName("p"))[0] );
insertBefore
needs the parent element. It won't function the way you are calling it (on body
), so I just looked up the "main" div instead.
Your problem is with document.body.insertBefore
, not with document.getElementsByTagName
-- you can see this for yourself by sticking the line
alert(document.getElementsByTagName("p")[0].innerHTML);
at the beginning of the script.
So what's going on with insertBefore
? It is a method of all DOM nodes, as you can see at that link, and it will only insert an element (or "document fragment") before one of the direct children of that node. When you have <div id="main>
in there, the <p>
found by getElementsByTagName
is not a direct child of the <body>
, so body.insertBefore
will not do what you want.
To get the effect you want, use instead
var first_p = document.getElementsByTagName("p")[0];
first_p.parentNode.insertBefore(myobj, first_p);
You have to specify the parent element, not document.body
for .insertBefore
.
<div id="main"><p>see</p></div>
<script type="text/javascript">
var myobj = document.createElement("div");
myobj.innerHTML='yesyes';
document.getElementById('main').insertBefore(myobj, document.getElementsByTagName("p")[0] );
</script>
you need to append child myobj before inserting it into body
document.body.appendChild(myobj);
精彩评论