开发者

how to apply jQuery element selection to a string variable

开发者 https://www.devze.com 2022-12-22 18:49 出处:网络
I have some html extracted to a string var, and want to then use jQuery element selection just on that string. Is this possible?

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 i开发者_如何学Cs 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


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


You could do something like:

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消