maxmitch
maxmitch

Reputation: 277

Remove input element by ID with javascript

I have done this and it doesn't seem to be working!:

Javascript:

<script>
function hideOptionPhoto(){ 
    var element = document.getElementById("Photo1");
    element.parentNode.removeChild(Photo);   
};

window.onload = function() {
    hideOptionPhoto();
};
</script>

HTML:

<div id=Photo1>
    <input id="Photo" type="image" src="x.png" border="0" name="submit" alt="">
</div>

I put the <input> inside a <div> because of the parent and child situation. Is that correct?

Upvotes: 3

Views: 43563

Answers (5)

Waruna Manjula
Waruna Manjula

Reputation: 3477

Try

function hideOptionPhoto(){ 
var element =  document.getElementById('Photo');
if (typeof(element) != 'undefined' && element != null)
  {
    element.remove();
    alert('Deleted');
  }

};

window.onload = function() {
    hideOptionPhoto();
};
<div id=Photo1>
    <input id="Photo" type="image" src="x.png" border="0" name="submit" alt="">
</div>

Upvotes: 0

AnaMaria
AnaMaria

Reputation: 3621

Ok. Let me post the working fiddle and the I will give the explanation.

Working Fiddle

In your code there was a "Syntax Error".

//Incorrect    
     <div id=Photo1>

//Correct
    <div id="Photo1">

In addition check my JavaScript function. The function call was ok. Just the code inside it was wrong

You already assigned the HTMLelement div(Photo1) to the variable "Element". The img("photo") is a child of Element and hence can be directly removed.

One more important point is the naming conventions that you use. You should not assign ID's like "photo"

HTML

<div id="Photo1">
    <input id="Photo" type="image" src="x.png" border="0" name="submit" alt=""/>
</div>

Javascript

function hideOptionPhoto(){     
    var element = document.getElementById("Photo1");
    var child=document.getElementById("Photo");
    element.removeChild(child);
};

window.onload = function() {
    hideOptionPhoto();
};

Upvotes: 1

Sikander
Sikander

Reputation: 656

<div id="Photo1">
<input id="Photo" type="image" src="x.png" border="0" name="submit" alt="">
</div>

Use this:

document.getElementById("Photo1").innerHTML = "";

Upvotes: -2

SarathSprakash
SarathSprakash

Reputation: 4624

Try this out. This will work

The below script should be put inside the body tag

<script>
function hideOptionPhoto(){


var element = document.getElementById("Photo1");
var child=document.getElementById("Photo");
element.removeChild(child);

}
window.onload = function() {
  hideOptionPhoto();
};
</script>

Upvotes: 10

user2625787
user2625787

Reputation:

var element = document.getElementById("Photo"); // notice the change
element.parentNode.removeChild(element);

The <div> is optional (for this) since every element has a parentNode. But there might be other reasons for having the div.

Upvotes: 6

Related Questions