Can't access id with getelementbyid

I have a string variable which contains an html value.

sAttachment = "<HTML><BODY><TABLE><TR id='tr1'><td>...</td></TR><TR id='tr2'><td>..</td></TR></TABLE></BODY></HTML>"

What I want to do is delete tr1 and all elements under it but I can't access it using getelementbyid.

var htmldoc = document.createElement('div');
htmldoc.innerHTML = sAttachment;

htmldoc.getElementById('tr1') --> object doesn't support this property or method.

Why can't I do this? or is there any other way so that I can remove tr1 without creating another element?

Using javascript. thanks in advance

Upvotes: 0

Views: 250

Answers (3)

PythonDev
PythonDev

Reputation: 4317

If it is just a string then you can do the below solution..

sAttachment = "<HTML><BODY><TABLE><TR id='tr1'><td>...</td></TR><TR id='tr2'><td>..</td></TR></TABLE></BODY></HTML>"

//convert string to JQuery element
var str = $(sAttachment);
//remove tr1 element
str.find('[id="tr1"]').remove()
//get back new string
var newStr = str.html();

Upvotes: 1

chandu
chandu

Reputation: 2276

using Jquery.

var $elem = $('#tr1');

It selects the TR what has the id of tr1

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388436

Because the Element object does not have a method called getElementById(), it is present in the document object.

Instead for modern browsers try to use the querySelector() method like

htmldoc.querySelector('#tr1')

Demo: Fiddle

Upvotes: 4

Related Questions