Search code examples
javascriptdynamic-datatraversal

Find a dynamic added tag with javascript


I am trying to see how to find a tag that was added dynamically within a table as so:

ParentTag= document.getElementById('parentdiv');
var newTag = document.createElement('div');
newTag.innerHTML="<span class="ImNew"></span>" 
ParentTag.appendChild(newTag);

How will I be able to find that tag in javascript, not leaning towards using jquery so no live recommendations please.. Trying to find that new tag in strictly javascript.

The tag I am referring to is the span tag


Solution

  • That depends on what other elements exist in the element. You can for example get all span tags in the element and filter out the ones with a specific class name:

    var parentTag = document.getElementById('parentdiv');
    var spans = parentTag.getElementsByTagname('SPAN');
    var filtered = [];
    for (var i=0; i<spans.length; i++) {
      if (spans[i].className === 'ImNew') filtered.push(spans[i]);
    }
    

    If there is only one span tag with that class name in the element, the filtered array now cotnains a reference to that element.