DEV Community

Cover image for javascript live and static selector
Chandra
Chandra

Posted on • Edited on

javascript live and static selector

Live selector

live selector track element in html document in active form if new element found in document then select that new element by active selector
list of live selector
1.document.getElementsByClassName()
2.document.getElementsByName()
3.document.getElementsByTagName()

<h1> live selector</h1>
<p class='first'>fisrt</p>
<p class='first'>second</p>
<p class='first'>third</p>
Enter fullscreen mode Exit fullscreen mode
var element = document.getElementsByClassName('first');

  for(let i=0;i<element.length;i++){
    console.log(i);
    }

setInterval(function(){
   for(let i=0;i<element.length;i++){
    console.log(i);
    }
},1000);

var newElmnt = document.createElement('p');
newElmnt.className='first';
var textNode = document.createTextNode('welcome to dev community ');
newElmnt.appendChild(textNode);

document.body.append(newElmnt);
Enter fullscreen mode Exit fullscreen mode
output
0
1
2
output after 1 second
0
1
2
3
Enter fullscreen mode Exit fullscreen mode

Static selector

Only one static selector in javascript
1.document.querySelectorAll()
Static selector select element from document in first time code execute after code execute any new element insert in document then static selector does not select new element

var element = document.querySelectorAll('.first');

  for(let i=0;i<element.length;i++){
    console.log(i);
    }


setInterval(function(){
   for(let i=0;i<element.length;i++){
    console.log(i);
    }
},1000);

var newElmnt = document.createElement('p');
newElmnt.className='first';
var textNode = document.createTextNode('welcome to dev community ');
newElmnt.appendChild(textNode);

document.body.append(newElmnt);

Enter fullscreen mode Exit fullscreen mode
output
0
1
2
output after 1 second are same 
0
1
2
Enter fullscreen mode Exit fullscreen mode

these are major difference between live and static selector
learn more about javascript tips please visit my website fast2learning

Top comments (0)