Eliminar texto y otros elementos antes y después del elemento

I need to delete everything (text and other elements) before and after the element <a> with value class chatlink. All this, within each element <div> with value class main.

Pero solo si <div> elemento con el valor main contains a link with the value of chatlink.

Por ejemplo:

<div class="main">
    Bla bla bla :)
    <a href="#" class="chatlink"><img src="#" /></a>
    bla bla bla ...
    <a href="#" class="chatlink"><img src="#" /></a>
    tra la la la laaa
    <a href="#" class="postlink">some text</a>

Código final:

<div class="main">
    <a href="#" class="chatlink"><img src="#" /></a>
    <a href="#" class="chatlink"><img src="#" /></a>

¿Es posible?

preguntado el 09 de marzo de 12 a las 16:03

I thank everyone for the answers. -

Damn, I forgot one important thing. Do this only if <div> elemento con el valor main contains a link with the value of chatlink :) -

6 Respuestas

Updated: and sorry for not understanding it correctly at the beginning

usa el siguiente código:

para legibilidad

        var currentDiv = $(this);
        var myLinks = $("a.chatlink", currentDiv);

quick with no intermediate variables

        $(this).html($("a.chatlink", $(this)));

Aquí se presenta una actualizado demostración de trabajo http://jsfiddle.net/Xxwt9/7/

respondido 09 mar '12, 17:03

Su uso de class="main" en lugar de id="main" implies there are several of them. Your proposed solution would make a proper mess in that case. - Deestán

You'd want to be "div.main" and "a.chatlink" rather than just ".main" and ".chatlink" - and you need to make sure that you're not catching chatlink links that are outside of "div.main". Also, I'd suggest using moves whenever possible, rather than clones. Certain dynamic jquery behaviors get a little wonky with cloning. Deestan's issue could then be fixed by hitting each of the divs individually with .each(). - ben barden

@Deestan: I've updated my proposed solution to take care of multiple divs - mohamed swillam

Also, you might want to change your 3rd line to something like "var mylinks = currentDiv.find('a.chatlink');" - I'm not quite sure what your current line does, but I don't think it's quite right. - ben barden

@BenBarden: actually this is a correct syntax. jQuery $ accepts a 2nd parameter to define the scope on which the selector should run. it's the same as your suggested code, but with different syntax :). - mohamed swillam

Search for all the text node within .main contenedor usando filter() y use remove() to remove them from the container or dom.

   return this.nodeType == 3 || !$(this).hasClass('chatlink');

Demostración de trabajo - http://jsfiddle.net/ShankarSangoli/Amjaq/3/

Tenga en cuenta que estoy usando contenido() método en $('.main') which gets the children of each element in the set of matched elements, including text and comment nodes. If you use any other find mechanism then textnodes are not considered.

respondido 09 mar '12, 17:03

"I need to delete everything (text and other elements)". I'll agree that the title is misleading, but there's not really any excuse for not reading the question properly. - antonio grist

But I also need to delete links and other elements that do not value class "chatlink". - Edoras

@AnthonyGrist - I hear you, thanks for that. I edited my answer. - ShankarSangoli

This is better? Ok, I use this. - Edoras

This works as long as there are no non-<div> nodes with class=main, and all of the a.chatlink nodes you want to save are direct children of said div.main nodes. Changing the '.main' selector to 'div.main' to eliminate the first caveat. - ben barden

It is possible. I believe the answer would be something like the following (though I may get it a bit wrong)


this assumes it is as you listed above, and all of the a tags you want to preserve are direct children of the div tags. It grabs all children of the div tags, unselects those that are a with chatlink class, and removes the rest from the DOM.

edit: changed from children() to contents() based on Shankar's correction.

respondido 09 mar '12, 17:03

Camino fácil

var links=$('.main a')​;

Aquí es un violín.

respondido 09 mar '12, 16:03

Con $('.main a.chatlink')​; that it works exactly as I wanted. Thank you. - Edoras

It is always better to remove what you don't need than DOM manipulation. - ShankarSangoli

this will not work if there are more than .main div inside your page. also this will get all the links, not just .chatlinks - mohamed swillam


$( '.main' ).contents().remove( ':not(.chatlink)' );

Demo en vivo: http://jsfiddle.net/wrUuw/

respondido 09 mar '12, 16:03

Select the elements you want to keep, detach them, empty the div, then reattach them.

var chatlinks = $(".main a.chatlink").detach();

respondido 09 mar '12, 16:03

Selector .main a.chatlink is incorrect - captures deeper child nodes than specified. Should be .main > a.chatlink. - Deestán

@Deestan he did not specify that all children would be direct children or that there would be multiple .main divs. Additionally, the question was modified after I posted my answer. - Kevin B

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