¿Cómo elimino elementos secundarios específicos dentro de un elemento de ID conocido?

I would like to be able to determine if a parent node, whose ID I know, has direct child nodes, and if such nodes are detected, remove them. The nodes, if they exist, will always follow some text, so I don't think I can use firstChild or lastChild.

Ideally, I would use Javascript to minimize the performance hit. Although JQuery would also work if necessary.

El código es así:

<a id="anchorID">some text 
<span class="spanClass">some span text</span>

Any help, as always, is appreciated.

preguntado el 01 de febrero de 12 a las 22:02

Using jQuery is a negligable performance hit, and will save you code and x-browser headaches. -

5 Respuestas

If you'd like to remove the child nodes in your anchor, and you're ok with jQuery, then it's quite simply:



You want to remove the span only?

$("#anchorID span").remove();

Eso eliminará todos spans in the anchor. If you wanted to remove only the first span, then you could do

$("#anchorID span:first").remove();

Respondido 02 Feb 12, 02:02

@Adma Rackis Sorry, but I should have been more specific that I need to leave the anchor text intact. - Robert Smith

That did it! Thanks very much. - Robert Smith

With jQuery and the HTML provided, it's as simple as $("#anchorId").remove(".spanClass");

Respondido 02 Feb 12, 02:02

plain ol js

var target = document.getElementById("anchorId");
  var children = new Array();
  children = target.childNodes();
  for(child in children)

Respondido 02 Feb 12, 02:02

With pure JavaScript use element.removeChild: http://jsfiddle.net/JetxN/

Respondido 02 Feb 12, 02:02

If you'd like not to remove top level textNodes (i.e. "some text" anchor text):


Respondido 02 Feb 12, 02:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.