Alex Rivera | Logout

jquery remove html elements inside variable (jquery object)

Asked 2013-03-07T11:24:27.830
13

Inside HTML I have this DIV:

<div class="teaser">
  <img src="thumb1.jpg"><img src="thumb2.jpg"><br>  // usually one thumb image; can be up to three
  some text goes here, sometimes not<br>
  <a href="example.html">always a link here</a><br>
  and sometimes another line here
</div>

I need to capture the content of the DIV minus the first line (the thumbs) in a variable to pass on as title (caption) to a lightbox script. However, in a day I've learned something about javascript & jquery (both are my weak spots), yet nothing I found by searching the web, including several threads here on stackoverflow, did it, either throwing errors or still including the thumbs or removing the text, too, or even removing the thumbs from the DOM:

// takes the whole
var teaser = $(".teaser");

// TypeError: $(...).html(...).find is not a function
var teaser = $(".teaser").find("img").remove();

// IMGs removed from DOM
var teaser = $(".teaser").find("img").remove();

// IMGs still included; I think I understand why
var teaser = $(".teaser").not("img");

// ditto
var teaser = $(".teaser").clone().not("img");

// ditto:
var teaser = $(".teaser");
$(teaser).find("img").remove();

// no teaser at all (everything removed, not just the IMGs)
var teaser = $(".teaser");
teaser = $(teaser).find("img").remove();

// ditto
var teaser = $(".teaser").clone().find("img").remove();

Changing the sequence in chainings didn't work either (though I may have missed one or another).

This workaround seems to be ok:

var teaser = $(".teaser").html().replace(/(<img.*?)+<br[^>]*?/i,"");

However, depending on regex implementation in browsers it might be shaky, so I'd rather have something more robust, particularly not getting the first line at all.

TIA for any suggestion - hope I could make myself clear.

Edit:<

Edit
Report

1 Answer

19

No need for html()

var teaser = $(".teaser").find("img").remove();

EDIT:

Try this:

var teaser = $(".teaser").clone();
teaser.find("img").remove()
// use teaser
answered 2013-03-07T11:27:07.633

Your Answer