Jake
Jake

Reputation: 1332

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

Upvotes: 1

Views: 431

Answers (3)

Guffa
Guffa

Reputation: 700322

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.

Upvotes: 1

Jonny Buchanan
Jonny Buchanan

Reputation: 62793

As others have mentioned, why not just keep track of it or give it an id if you're going to need it later?

But anyway, this is how you could do a manual search (searching from back to front as you're adding the new items to the end).

var parent = document.getElementById("parentdiv")
for (var i = parent.childNodes.length - 1; i >= 0; i--)
{
    var el = parent.childNodes[i];
    if (el.nodeType == 1 &&
        el.nodeName.toLowerCase() == "div" &&
        el.firstChild &&
        el.firstChild.nodeName.toLowerCase() == "span" &&
        el.firstChild.className = "ImNew")
    {
        // el.firstChild is what you want
    }
}

Upvotes: 1

Justin Ethier
Justin Ethier

Reputation: 134157

You could give your new tag an ID when you create it:

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

Then later, just use that ID to find it:

var newTag = document.getElementById('myNewID');

Upvotes: 2

Related Questions