hguser
hguser

Reputation: 36018

How to get the outerHTML of the current selected element in jquery

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`.
  }
});

Upvotes: 1

Views: 1237

Answers (5)

Stiger
Stiger

Reputation: 1199

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.

Upvotes: 1

Nagarjun
Nagarjun

Reputation: 2466

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/

Upvotes: 1

Edward
Edward

Reputation: 1914

You can try .find()

$("#t").find('.xx,.yy')

Upvotes: 0

p e p
p e p

Reputation: 6674

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/

Upvotes: 2

Khanh TO
Khanh TO

Reputation: 48972

$("#t a.xx,#t a.yy").each(function(){
    $('<div>').append($(this).clone()).html();
});

Upvotes: 1

Related Questions