how to concatenate two getElementsBy
I have a snippet of code like this:
var profileLinks = new Array();
for (var i = 0; i<searchResult.length; ++i)
{
var profileLink=searchResult[i].getElementsByTagName("a");
profileLinks[i]=profileLink[0].href;
alert(i+1+" of "+se开发者_JS百科archResult.length+" "+profileLinks[i]);
}
It seems like I should be able to make it more concise by using this:
//alternate construction (why doesn't this work?)
var searchResult = document.getElementsByClassName("f_foto").getElementsByTagName("a");
What's wrong here?
Use querySelectorAll()
instead:
var searchResult = document.querySelectorAll(".f_foto a");
IE 8 supports querySelectorAll()
but not getElementsByClassName()
, so this should give you better compatibility too.
For full compatibility, stick to your original code or use a library like jQuery.
document.getElementsByClassName("f_foto")
returns a selection, therefore you cannot chain functions to it. You need to specify an element directly not a whole selection, for example this would work correctly.
document.getElementsByClassName("f_foto")[0].getElementsByTagName("a");
Because document.getElementsByClassName("f_foto")[0] points to an object and not to a selection of objects.
This is why we have libraries - or even modern browsers. You are looking for the css selector $('.f_foto a')
in jQuery, or $$('.f_foto a')
in Prototoype/Chrome
You call getElementsByTagName on a node, not an array, which is what is returned by getElementsByClassName.
I believe that getElementsByTagName
can only be applied to an element node, but the result of getElementsByClassName
is surely going to be a list of nodes. You'll either have to pick one ([0]
?) or iterate over the collection (make sure it's not empty!).
精彩评论