+ 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>

27th Mar 2018, 6:16 PM
Abdul Basit
Abdul Basit - avatar
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; }
27th Mar 2018, 6:20 PM
Toni Isotalo
Toni Isotalo - avatar
+ 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!!
27th Mar 2018, 6:32 PM
*** - avatar
+ 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)'...
27th Mar 2018, 7:28 PM
visph - avatar
- 3
$('#chain .key span')[0] will be selected first element . it's array.
28th Mar 2018, 7:05 AM
Amalia Greenberg
Amalia Greenberg - avatar
- 4
<div id="chain"> <span>Practicando</span> </div>
9th Apr 2018, 11:26 PM
Anderson Victor Romero Santos
Anderson Victor Romero Santos - avatar