So when the code ...
document.getElementById('classhere').childNodes
... runs, I manage to get all elements with that ID EXCEPT for elements that have been dynamically created by a 'createDiv()' function:
function createDiv()
{
var divTag = document.createElement("div");
divTag.id = "classhere" + num;
...
I would like to get all div elements with that Id, even dynamically created div el开发者_运维技巧ements. Does anyone have a solution? Thanks!
Try out jQuery jQuery Wildcard Selector http://www.emadibrahim.com/2009/07/25/jquery-wildcard-selector/
So when the code ...
document.getElementById('classhere').childNodes
... runs, I manage to get all elements with that ID
getElementById
looks up a single element by ID, not by class. That line as quoted will look up an element with the id
value "classhere" and return a NodeList
of its immediate child nodes (elements, text nodes, etc.). If you create further elements and either don't add them to the DOM, or add them elsewhere (not as immediate children of the "classhere" element), they won't be on the NodeList
. It has nothing to do with whether they were created during the main HTML parsing or after-the-fact with JavaScript.
I would like to get all div elements with that Id...
There can be only one element with a given ID.
If you're trying to find all elements whose id
starts with "classname", you can use an "attribute starts with selector":
var divs = $("div[id^='classname']");
...gives you a jQuery object containing all of the matching divs as of the time you executed the statement (unlike a NodeList
, it's not live; if you change things you'll have to run the selector again).
精彩评论