getElementByClass does it exist in vanilla js? uhn?
<p id ="myP">
Render this text using the myC class </p>
---------------------------
.teststyle {
background-color:#00ff00;
font-size: 200%;
}
---------------------
window.onload = load;
function load(){
document.getElementById("myP").className = "teststyle";
}
----------------------
Playing with jsfiddle.net and JavaScript I found out that getElementByClass
is not supported in JS. I'm wondering why? What if I had a class in my XTHML-code, how can I transform this code?
The other peculiar thing I noticed is: if I use onload = "load()"
in the xhtml won't work like if I had "windows.load"
in the js-code; why is that? It should be the same, maybe开发者_开发知识库 it's just me.
No it doesn't, because the function's name is:
getElementsByClassName
// ^ ^^^^
Note that it is not support in IE before IE9.
Have a look at the documentation of getElementsByClassName
.
Regarding the onload
issue: Without more code it is hard to tell what you did wrong. If you do
<body onload="load()">
it will work. But doing so (attaching event handlers in the HTML) should be avoided anyway.
I found out that "getElementByClass" is not supported in JS, uhn? funny wondering why?
Because JS has no native DOM manipulation in it. That's a separate API (provided by browsers, some other JS environments, and libraries for those other environments).
… but you probably count browser DOM implementations as part of JS for the purpose of this question so:
Because class
isn't a generic DOM concept, it is HTML specific (or at least started out that way). getElementsByClassName
(note Name!) is new in draft specifications and not all browsers have implemented it.
so what if I had a class in my XTHML-code how can I transform this code?
You don't use getElementsByClassName in that code, so it doesn't really make much sense.
There are plenty of third party libraries that provide means to get elements based on the classes to which they belong. Some have implementations of getElementsByClassName, some just implement selector engines (such as YUI and jQuery).
The other peculiar thing I noticed is: if I use onload = "load()" in the xhtml won't work like if I had "windows.load" in the js-code...how is dat? it should be the same, maybe it's just me..thanks!
One will overwrite the other.
function getElementsByClassName( strClassName, obj ) {
var ar = arguments[2] || new Array();
var re = new RegExp("\\b" + strClassName + "\\b", "g");
if ( re.test(obj.className) ) {
ar.push( obj );
}
for ( var i = 0; i < obj.childNodes.length; i++ )
getElementsByClassName( strClassName, obj.childNodes[i], ar );
return ar;
}
Usage :
var aryClassElements = getElementsByClassName( 'findMe', document.body );
From : http://www.tek-tips.com/viewthread.cfm?qid=1143850&page=1
Do you guys search on google before posting here ?
精彩评论