简体   繁体   中英

What's the best way to get a list of the contents of a specific group of DOM elements in javascript?

The basic scenario: I've got a series of elements on an HTML page, generated dynamically. (Currently, they're all divs , but they don't need to be.)

What I want is a javascript function that will loop though all of those divs (or whatever) looking for the presence of a specific value.

What's the best, most cross-browser way to do this? Does getElementsByName() work on divs in all browsers? Can I give them all the same ID and get an array back out of getElementById somehow?

If I change those divs to spans or inputs , does that make things easier?

Thanks!

(edit: it would be best, for this project, if there was a solution without using any external js libraries. I assume jQuery has a function that does just this in one line, but for the moment I'd like to avoid opening that can of worms with the client.)

getElementsByTagName is defined in DOM Core, so any browser which implements that works. That's about every browser in current use.

Take a gander over here for the specifics: http://www.quirksmode.org/dom/w3c_core.html

One gotcha to be ware of, is that getElementsByTagName returns a NodeList - not an array. It works the same, but it is evaluated very late, so if you add/remove nodes to the DOM while traversing a NodeList , you will get weird results. In these cases, write two loops; First loop through the NodeList and store all entries in an array - Then loop through the array.

It doesn't matter what the elements are, but what does matter is where they are in the page. If they are all child elements of a single parent element, your problem is simple. Give the parent element an ID and you can use getElementById() to grab it and iterate its children.

getElementById() behavior is undefined when more than one instance of an ID is found in the document. Most will return the first Element they can find, but you certainly can't cound on getting an array.

getElementsByTagName() will work only if you can use some obscure tag that you are sure won't appear elsewhere in your page. You could augment this by specifying that the elements you are interested in will have an attribute present that you can check for (such as @class or @title). You can then loop through the result of getElementsByTagName() checking for this and only look at Elements where the attribute is present.

You can use this site to see what getElementBy most suites your needs.
There are some using libraries and some like troelskn wrote that apply for standard javascript in all supporting browsers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM