How to apply jQuery element to string variable

I have some html extracted to a var string and you want to then use the jQuery element select only on that string. Is it 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 tags from the <a> tag in myHtml .

thanks

+6
jquery jquery-selectors
source share
4 answers

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

 // 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(); 
+10
source share

You can do something like:

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

There is a jQuery plugin ( here ) that you can use to parse a string as an XML DOM, and then use jQuery to query, This should be XML, not the β€œrelaxed” kind of XML that you sometimes see in HTML, though (i.e. e. You need quotes around your attribute values).

0
source share

If you need to process multiple elements 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
source share

All Articles