Michael Freidgeim wrote:
Ivo,
Thank you for your reply.
But META tag has name attribute, not ID and even formally should not be
considered by getElementById. META names and body control IDs are quite
different entities and should not be used in the same namespace.
However let's re-phrase my question: which function should I use/create
for the equivalent of getElementById on the
document.body level?
The problem is that Internet Explorer will use NAME attributes for
getElementById( ) lookups, which you've discovered. Ultimately the solution
would be to try to avoid conflicts and ensure that all NAMEs and IDs on the
page are unique. If this is not an option, then the following code will
produce the correctly IDed <DIV> on the <BODY> (even if there are multiple
items with the same name that are not DIVs):
<html>
<head>
<title>Test</title>
<meta name="keywords" content="This is a test META" />
</head>
<body onload="test('k eywords');">
<div id="keywords">T his is a test DIV</div>
<script type="text/javascript">
function test(theId) {
// retrieve the element
var el = document.getEle mentById(theId) ;
// test to ensure it's the kind of tag you want
if (el.tagName.toU pperCase() != 'DIV') {
// if it is not the kind of tag you want, retrieve
// all the tags of the type you want
var divs = document.getEle mentsByTagName( 'DIV');
// loop through all the tags of the type you
// want until you find the id you want
for (var i = 0; i < divs.length; i++) {
if (divs[i].id == theId) {
// you found the id you want, assign
// it to "el" and stop looking
el = divs[i];
break;
}
}
}
if (el) {
// if you've successfully retrieve "el", use it
alert(el.firstC hild.nodeValue) ;
}
}
</script>
</body>
</html>
The code could be made less complex by always retrieving
getElementsByTa gName(), but I think the getElementById( ).tagName test is
worth the trouble, considering many browsers will correctly identify the
tagName you want and bypass the loop. Also, if you don't want to identify a
DIV, it should be easy enough to change the code to retrieve the tagName
you do want (or better yet, make it a parameter you can pass to the
function), like:
function getElementByIdO rNameAndTagName (idOrName, tagName) { ...
and call it with:
var el = getElementByIdO rNameAndTagName ('keywords', 'DIV');
--
Grant Wagner <gw*****@agrico reunited.com>
comp.lang.javas cript FAQ -
http://jibbering.com/faq