1

Given the htmls:

<div id="t">
   <a class="xx">xx</a>
   <a class="yy">yy</a>
   <a class="zz">zz</a>
</div>

Now how about if I want to get the links whose class is xx or zz, that's to say I want to get this:

   <a class="xx">xx</a>
   <a class="zz">zz</a>

I tried this:

$("#t a").each(function(){
  if($(this).is(".xx,.yy"){
    //here how to get the out the HTML of the current a element?
  }
});

Any alternatives?

I noted that there are two answers, but it seems that they misunderstand me.

$("#t a").each(function(){
  if($(this).is(".xx,.yy"){
    //here I want to get the full HTML of the `a` element
    // That's to say, I want to get `<a class="xx">xx</a>`

     // I can not use $(this).html() or $(this).text() which will only return the `xx`.
  }
});
p e p
  • 6,593
  • 2
  • 23
  • 32
hguser
  • 35,079
  • 54
  • 159
  • 293

5 Answers5

2

The other answers are incorrect. Here is exactly how you'd get it.

$('a.xx,a.yy').each(function(index, currentLink){
   var z = currentLink.outerHTML;   //z will be <
});

Another solution, using jQuery to get the anchor HTML:

$('a.xx,a.yy').each(function(index, currentLink){
   alert($(currentLink.outerHTML).wrap('<p/>').parent().html());
});

Here's the jsfiddle http://jsfiddle.net/wabjw/

p e p
  • 6,593
  • 2
  • 23
  • 32
  • I'm not 100% sure, but I updated my answer to include a jQuery solution which should work since it looks like you are using jQuery already. – p e p Jun 07 '13 at 06:34
1
$("#t a.xx,#t a.yy").each(function(){
    $('<div>').append($(this).clone()).html();
});
Khanh TO
  • 48,509
  • 13
  • 99
  • 115
1
var html = '';
$('#t a.xx, #t a.zz').each(function(){
  html += $(this).wrap('<p/>').parent().html();
  $(this).unwrap();
});

JS Fiddle: http://jsfiddle.net/rwGsR/9/

Nagarjun
  • 2,346
  • 19
  • 28
1

Is this correct?

JS:

$("#t a").each(function(){
  if($(this).is(".xx,.yy")){
    console.log(this.outerHTML);
  }
});

It return: "<a class=\"xx\">xx</a>" & "<a class=\"yy\">yy</a>" in console.

Stiger
  • 1,189
  • 2
  • 14
  • 29
0

You can try .find()

$("#t").find('.xx,.yy')
Edward
  • 1,914
  • 13
  • 26