views:

162

answers:

4

I have some html extracted to a string var, and want to then use jQuery element selection just on that string. Is this possible?

For example:

HTML:

<div class=message>
  This is a message. Click <a class=link id=link1 href=example.com>here</a>
</div>

jQuery:

$('div.message').each(function(i, item) {
  myHtml = $(this).html();
  //select <a> tag attributes here
)};

So in this example, I want to extract the id and href from the <a> tag in myHtml.

Thanks

A: 

You could do something like:

var aID = $('div.message a.link').attr('id');
var aHREF = $('div.message a.link').attr('href');
Dustin Laine
@durilai Yes, I could do that but it is not optimal in this situation.
Why? It achieves what you are looking for.
Dustin Laine
@uku that is the best way...
joberror
A: 

There is a jQuery plugin (here) that you can use to parse a string as an XML DOM and then use jQuery to query it. It needs to be XML, not the "relaxed" kind of XML that you sometimes see in HTML, though (i.e. you need quotes around your attribute values).

Dean Harding
A: 

If you need to process multiple items within your structure you can do this

$('div.message').each(function(i, item) { 
  // find desendant of the item using "find"
  var alink = $(this).find('a.link');
  // Process the item
  var id = alink.attr('id'); 
  var href = alink.attr('href'); 
)}; 
Marty Trenouth
Find method is recursive and would not use it unless you need to.
Dustin Laine
+2  A: 

If I understand correctly, you have HTML code in a string variable, and want to query within that?

// Suppose you have your HTML in a variable str
var str = '<div class="message">This is a message. Click '
        + '<a class="link" id="link1" href="example.com">here</a></div>​​​​​​​​​​​​​​​';

// You query the DOM fragment created by passing the string to jQuery function.
// $(<string>) - creates a DOM fragment (string must contain HTML)
var anchor = $('a', $(str));

// Then you can retrieve individual properties and/or contents:
var id = anchor.attr('id');
var href = anchor.attr('href');
var text = anchor.text();
Marko Dumic
This looks promising. I will give it a try.
+1 - The only answer that applies to the question.
Nick Craver
@Nick Craver, how is this different than my response. Other than the selector. I am trying to understand. Thanks
Dustin Laine
@durilai - Your answer selects on the DOM element (as if it exists in the current document)...that's the main difference to the question, uku wants to select elements from any string of HTML which this does by using the context argument of the selector.
Nick Craver
@Nick Craver, thanks for the explanation. I see your what you are saying. :)
Dustin Laine
@Marko Dumic - Thanks, very nicely done.