how to apply jQuery element selection to a string

2019-04-07 21:06发布

问题:

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

回答1:

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();


回答2:

You could do something like:

var aID = $('div.message a.link').attr('id');
var aHREF = $('div.message a.link').attr('href');


回答3:

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).



回答4:

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'); 
)};