Reputation: 1391
Someone suggested me to use document.querySelectorAll("#tagContainingWrittenEls > *")
to get a reference to all the written tags. Then you can loop over 'em all, and do .tagName
and .attributes
on each element in the list to get the info.
But This can only be done if there is a class named #tagContainingWrittenEls. I thought this is some method
Upvotes: 3
Views: 17331
Reputation: 119897
According to MDN, .querySelectorAll
Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.
.querySelectorAll returns a list of elements that match the selector provided.
it's like how you style in CSS: you create a selector, put in the properties you want to apply to these target elements then these elements get styled.
say in CSS, you want to style all <a>
in <li>
that are under <ul>
with an id
of list
with the color red
. You will have this:
ul#list li a{
color:red;
}
in effect, all <a>
in an <li>
under a <ul>
with an id
of list
turns to red.
now take that same selector to get via JavaScript these same <a>
elements
var anchors = document.querySelectorAll('ul#list li a');
now anchors
will contain a NodeList
(an array-like structure) that contains a reference to all <a>
in an <li>
under a <ul>
with an id
of list
. Since a NodeList
is like and Array
, you can loop through it, and each item is an <a>
in an <li>
under a <ul>
with an id
of list
.
and of course, it only gets the elements that are in the DOM at the time the code is executed.
Upvotes: 2
Reputation: 116050
The querySelectorAll
function takes a selector string returns a NodeList
which can be iterated through like an array.
// get a NodeList of all child elements of the element with the given id
var list = document.querySelectorAll("#tagContainingWrittenEls > *");
for(var i = 0; i < list.length; ++i) {
// print the tag name of the node (DIV, SPAN, etc.)
var curr_node = list[i];
console.log(curr_node.tagName);
// show all the attributes of the node (id, class, etc.)
for(var j = 0; j < curr_node.attributes.length; ++j) {
var curr_attr = curr_node.attributes[j];
console.log(curr_attr.name, curr_attr.value);
}
}
The breakdown of the selector string is as follows:
#nodeid
syntax refers to a node with the given id. Here, the
hypothetical id of tagContainingWrittenEls
is used -- your id will probably
be different (and shorter).>
syntax means "children of that node".*
is a simple "all" selector.Taken all together, the selector string says "select all children of the node with the id of "tagContainingWrittenEls".
See http://www.w3.org/TR/selectors/#selectors for a list of CSS3 selectors; they are quite important (and handy) to advanced Web development.
Upvotes: 7