开发者

How can I call an element from an array created by "document.getElementBytag()"?

开发者 https://www.devze.com 2023-02-26 23:58 出处:网络
I am trying to make a page work for my website using the mootools framework. I have looked everywhere I can think of for answers as to why this isn\'t working, but have come up empty.

I am trying to make a page work for my website using the mootools framework. I have looked everywhere I can think of for answers as to why this isn't working, but have come up empty.

I want to populate several arrays with different data types from the html, and then, by calling elements from each array by index number, dynamically link and control those elements within functions. I was testing the simple snipp开发者_Go百科et of code below in mootools jsfiddle utility. Trying to call an element from array "region" directly returns "undefined" and trying to return the index number of an element returns the null value of "-1".

I cannot get useful data out of this array. I can think of three possible reasons why, but cannot figure out how to identify what is really happening here: 1. Perhaps this array is not being populated with any data at all. 2. Perhaps it is being populated, but I am misunderstanding what sort of data is gotten by "document.getElementBytag()" and therefore, the data cannot be displayed with the "document.writeln()" statement. (Or am I forced to slavishly create all my arrays?) 3. Perhaps the problem is that an array created in this way is not indexed. (Or is there something I could do to index this array?)

html:

<div>Florida Virginia</div>

<div>California Nevada</div>

<div>Ohio Indiana</div>

<div>New York Massachussetts</div>

<div>Oregon Washington</div>

js:

var region = $$('div');

document.writeln(region[2]);

document.writeln(region.indexOf('Ohio Indiana'));

Thanks for helping a js newbie figure out what is going on in the guts of this array.


$$ will return a list of DOM elements. If you are only interested in the text of those DOM nodes, then extract that bit out first. As @Dimitar pointed out in the comments, calling get on an object of Elements will return an array possibly by iterating over each element in the collection and getting the property in question.

var region = $$('div').get('text');

console.log(region[2]);                      // Ohio Indiana
console.log(region.indexOf('Ohio Indiana')); // 2

Also use, console.log instead of document.writeln or document.write, reason being that calling this function will clear the entire document and replace it with whatever string was passed in.

See an example.

0

精彩评论

暂无评论...
验证码 换一张
取 消