Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to apply jQuery element selection to a string variable

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

like image 361
user191688 Avatar asked Mar 11 '10 00:03

user191688


People also ask

How do you select elements in jQuery?

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.

How do you select elements with a particular class selected?

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.


1 Answers

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();
like image 152
Marko Dumic Avatar answered Oct 26 '22 07:10

Marko Dumic