简体   繁体   中英

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!

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;');
});

Replace your code with this:

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

jsFiddle

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.

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>');
});
$('.test a').click(function(){
    return false; 
});

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

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>");
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM