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
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
If you want to select elements with a certain class, use a dot (.) and the class name. You can also use the class selector in combination with a tag name to be more specific.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With