0

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));
2
  • 1
    Is it a typo or you forgot to close the el? $(el).find....? Commented Apr 30, 2013 at 0:05
  • Nope, it wasn't, i have added that back in- although it still calling the same error. Commented Apr 30, 2013 at 0:09

3 Answers 3

2

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>');  
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This worked and found all the tags. I assume if I want a different newtag for each one it finds, I would use the index and pass in a number, so 0 for the first article it finds, 1 for seconds, etc.
0
(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.

1 Comment

Thanks kcdwayne. I'm not getting any errors anymore, but its not doing anything. Am I searching for the tags correctly in that find statement, or is it just looking for the words "heading img"?
0

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/

1 Comment

Sorry I did something dumb, edited to remove a superfluous $(..)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.