Reputation: 21150
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
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');
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;
});
Upvotes: 3
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
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