Reputation: 28799
<li id="ioAddOtherRelation">
<a href="" onclick="return ioAddSetOtherRelation()"class="smallLink">add other relation</a>
</li>
and i want the function ioAddSetOtherRelation to remove the a tag
function ioAddSetOtherRelation(){
var bigLi = document.getElementById('ioAddOtherRelation');
bigLi.removeChild(bigLi.childNodes[0]);
return false;
}
when i press the link for the first time ,nothing happend , but when i press it twice it remove the a tag , i want to remove the a tag in one click
Upvotes: 0
Views: 272
Reputation: 309
The problem with the code you posted is that the first child of your 'li' element is actually a textNode containing the newline and whitespace between itself and the 'a' element. The first time you click, this invisible textNode is removed and the second time you click the 'a' is removed.
You can demonstrate this by removing the newline and whitespace (i.e. put all the HTML on one line with no spaces) - you should see the 'a' disappearing on the first click.
I found that the following modified javascript worked as you intended. Note I've used .getElementsByTagName() to make sure that only 'a' elements are returned. this will return an array like .childNodes would, so I'm taking the first element of the resulting array.
function ioAddSetOtherRelation() {
var bigLi = document.getElementById('ioAddOtherRelation');
bigLi.removeChild(bigLi.getElementsByTagName("a")[0]);
return false;
}
I found FireBug to be very useful in solving this problem (together with console.debug() lines in the JS code) - if you're not already using that I'd recommend giving it a go!
Upvotes: 2
Reputation: 4368
Use jQuery and send parameter as this
Take that this
in ioAddSetOtherRelation function
Check it here
Upvotes: 1
Reputation: 943556
The first time you clicked you removed the text node containing the space in front of the element. You need to make sure the argument you pass to removeChild
is the one you actually want.
This would be a saner approach to the problem:
<li id="ioAddOtherRelation">
<a href="" onclick="return ioAddSetOtherRelation(this)" class="smallLink">add other relation</a>
</li>
function ioAddSetOtherRelation(element){
var bigLi = element.parentNode;
bigLi.removeChild(element);
return false;
}
Getting rid of the intrinsic event attribute and writing unobtrusive JavaScript would be better still.
Upvotes: 3