+ 3
how to select span within div
How to select span within div one by one? like first I want to target span1 then 2 and so on <div class="key" id="chain"> <span></span> <span></span> <span></span> </div>
5 Answers
+ 4
var spans = document.getElementById("chain").getElementsByTagName("span");
for(var a = 0; a < spans.length; a++) {
var target = spans[a];
target.innerHTML = a;
}
+ 2
Maybe try and look up for Jquery if you want to do it in Javascript
In css you can refer to it as:
span {
....
}
This means you will effect all spans in the document!!
+ 2
With css selectors, you can target each <span> direct childs of a specific element by:
#chain > span:nth-child(n)
... where n is the index (started at 1) of yours spans.
'>' operator is required to target only direct childs, else you could select also deeper childs:
#chain span:nth-child(2) { color:red; }
with:
<div id="chain">
<span>I'm not styled</span>
<span>I'm red</span>
<p>
<span>I'm not styled</span>
<span>I'm red also as I'm second child of p which is child of #chain</span>
</p>
</div>
You could also use ':first-child', ':last-child' for first and last child, and also look at specificity of ':first-of-type', ':last-of-type', and 'nth-of-type(n)'...
- 3
$('#chain .key span')[0] will be selected first element . it's array.
- 4
<div id="chain">
<span>Practicando</span>
</div>