Adam
Adam

Reputation: 2997

Finding tags within tags in jquery and replacing content

I have four article tags in my html page with the class col. Inside each article I have a div with the class heading. Inside of that I have an img tag.

I'm trying to iterate through each artcle and remove that image tag and replace with some different html.

This in Wordpress, hence the funky jquery function wrapper.

Right now im just trying to get the finding and replacing working (below) - I haven't attempted the different code for each article bit yet. I can't figure out why the below doesn't work.

(function ($) {
  $(document).ready(function() {
    $('article.col').each(function(el) {
      $((el).find('heading img').replaceWith('<newtag>somecode</newtag>'));  
    });
  });
 }(jQuery));

Upvotes: 0

Views: 81

Answers (3)

Aaron K
Aaron K

Reputation: 437

There are a few problems with the syntax,

$(el.find('heading img').replaceWith('<newtag>somecode</newtag>')); 

should be

$(this).find('heading img').replaceWith('<newtag>somecode</newtag>'); 

see this fiddle:

http://jsfiddle.net/5bEq7/1/

Upvotes: 0

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

When calling each, the function value are function(index, element). So right now, you are trying to search a number with $(el), try $(this) or add an other argument to your function.

also, the dot is missing for the class heading

$('article.col').each(function(index, el) {
   $(el).find('.heading img').replaceWith('<newtag>somecode</newtag>');  
});

or

$('article.col').each(function() {
    $(this).find('.heading img').replaceWith('<newtag>somecode</newtag>');  
});

Upvotes: 2

Casey Dwayne
Casey Dwayne

Reputation: 2169

(function ($) {
  $(document).ready(function() {
    $('article.col').each(function(el) {
       $(this).find('heading img').replaceWith('<newtag>somecode</newtag>');  
   });
  });
 }(jQuery));

Btw, the jQuery wrapper is to prevent conflicts with other libraries using the $ symbol.

Upvotes: 0

Related Questions