FlyingCat
FlyingCat

Reputation: 14290

Select all links with certain elements

I want to select the a tag under some divs

my html

<div class='test'>
   <div> 
      <div>
         <a href='#'> bunch of stuff1  </a>
         <a href='#'> bunch of stuff2  </a>
         <a href='#'> bunch of stuff3  </a>
      </div>     
   </div>
</div>

I want to replace the above html to

<div class='test'>
   <div> 
      <div>
         <a href='#' class='beam' onclick='return false;'> bunch of stuff1  </a>
         <a href='#' class='beam' onclick='return false;'> bunch of stuff2  </a>
         <a href='#' class='beam' onclick='return false;'> bunch of stuff3  </a>
      </div>     
   </div>
</div>

My code:

 var texts =$('.test')

 texts.children().children().find('a').each(function(){
        var text = $(this).text();
        $(this).replaceWith("<a href='#' class='beam' onclick='return false;'>" + text + "</a>");
    })

The above codes don't seem to work. I can't change any of the html structure nor giving those div id or class. Thanks for the help!

Upvotes: 1

Views: 98

Answers (6)

Brian Rogers
Brian Rogers

Reputation: 129817

Replace your code with this:

$('.test div div a').addClass('beam').click(function() {
    return false; 
});

jsFiddle

Upvotes: 1

StackSlave
StackSlave

Reputation: 10617

Try the following:

$('.test>div>div>a').each(function(){
  var txt = $(this).text();
  $('.test>div>div').html("<a href='#' class='beam' onclick='return false;'>"+txt+'</a>');
});

Upvotes: 1

Acorn
Acorn

Reputation: 867

If you're looking to just add some attributes, you can do something like this as well:

$('.test a').attr({'class:beam', 'onclick':'return false;'});

Seems like there are already some answers here that will help you achieve the same result, but you don't need to loop through the tags with .each() to do it.

Upvotes: 1

Tuanderful
Tuanderful

Reputation: 1319

Modify your JS as follows:

var texts = $('.test')

texts.find('a').each(function(){
  $(this).addClass('beam').on('click', function(){
    return false;
  });
});

jsFiddle available here: http://jsfiddle.net/pbwDV/

You can further simplify texts.find('a') to $('.test').

This loops through your anchors, uses addClass to add the classname. If you don't want to use .on('click') I suppose you can also use .attr('onclick','return false;') and your JS would look something like this:

$('.test a').each(function(){
  $(this).addClass('beam').attr('onclick','return false;');
});

Upvotes: 1

kashimu
kashimu

Reputation: 174

just remove the .children().children()

var texts =$('.test')

 texts.find('a').each(function(){
        var text = $(this).text();
        $(this).replaceWith("<a href='#' class='beam' onclick='return false;'>" + text + "</a>");
    })

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50798

$('.test a').click(function(){
    return false; 
});

This is the same as above, but done in jQuery.

Upvotes: 0

Related Questions