JVG
JVG

Reputation: 21150

Use jQuery to select an element that is contained within a comment

I have a bit of a strange question, I'm wondering whether this is at all possible.

I'm parsing the DOM and there is an element like this:

<!-- <a class="pager" title="next" href="www.text.com">NEXT</a> -->

I need to be able to select this element with jQuery and return its href value. I've tried this:

$('a.pager[title="Next"]').attr('href');

but to no avail - from reading here Selecting HTML Comments with jQuery it seems that jQuery can only select elements with a particular nodetype.

Is it possible to return the value www.text.com from the HTML element above? To make things a little more tricky, i need to do it without relying on jQuery plugins - native Javascript or plain jQuery only please.

The following code returns the whole comment (as well as the text contained in all other comments on the page):

$("*")
    .contents()
    .filter(function(){ return this.nodeType == 8;})
    .each(function(){ alert(this.nodeValue);});

but I need to ONLY return the value of the a href, and no other comments. Ideas?

Upvotes: 2

Views: 2379

Answers (3)

adeneo
adeneo

Reputation: 318232

Actually, all you have to do is trim it :

var markup = $("*").contents().filter(function(){ 
    return this.nodeType == 8;
}).get(0).nodeValue;

var href = $($.trim(markup)).attr('href');

FIDDLE

EDIT:

to make it more specific you could always do some string matching :

var markup = $("*").contents().filter(function(){ 
    return this.nodeType == 8 && this.nodeValue.indexOf('class="pager"') != -1;
});

EDIT AGAIN:

You could also do :

var href = $.map($("*").contents(), function(el) {
    var html   = $.parseHTML( $.trim(el.nodeValue) ),
        anchor = $('<div />').append(html).find('a.pager[title="next"]');

    return el.nodeType === 8 && anchor.length ? anchor.attr('href') : null;
});

FIDDLE

Upvotes: 3

codetantrik
codetantrik

Reputation: 315

$("*")
    .contents()
    .filter(function(){ return this.nodeType == 8;})
    .each(function(){
        var regex = new RegExp('href=\"(.*)\"','g');
        var hrefValue = regex.exec(this.nodeValue)[1];
        alert(hrefValue);
    });

Upvotes: -1

John Dvorak
John Dvorak

Reputation: 27287

After selecting the comments, you need to parse their text content as HTML before you can reliably traverse the encoded DOM:

var matches = [];
$("*").contents().each(function(){
  if(this.nodeType != 8) return;
  var $div = $("<div>");
  $div.append(this.nodeValue);
  $div.find("a.pager[title='next']").each(function(){
    //replace $(this).attr("href") with this.href if you don't mind
    //relative URLs getting converted to absolute URLs
    matches.push($(this).attr("href"))
  });
});

Upvotes: 2

Related Questions