tags:

views:

48

answers:

3

I am new to JQuery, so this may be a stupid question, however I have not been able to find a solution.

I have a raw HTML string stored as a JS variable, as shown below. What I would like to do is parse the HTML string as a DOM object, and be able to access and change any children within the div by their id.

So, I would need to access "ht" and "vt" by id after the raw HTML is parsed. How would I perform this?

var htmlStr = "<div><span id='ht'>test 1</span><span id='vt'>test 2</span></div>";
$(htmlStr).ht // Something like this, that would return "test 1"

I am basically trying to use some raw HTML as a template for creating items in an unordered list. I would create the new list item using the template, and then replace certain portions of the template with data from a web service.

Thanks

+1  A: 

Try this:

$("#ht",htmlStr).html()
jigfox
+2  A: 

Given your example, you could do.

var htmlStr = "<div><span id='ht'>test 1</span><span id='vt'>test 2</span></div>";
var htContent = $('#ht', htmlStr).text();

Basically, you are getting an element with the ID of ht, from within the context of the <div> stored in your htmlStr variable.

Then, you are retrieving its text content with .text(). Alternatively, you could retrieve any html tags as well with .html().


EDIT:

If you are going to do much work with that html string, you can store it in a jQuery object, and do whatever you want, even though it hasn't yet been inserted into the DOM

var $htmlStr = $("<div><span id='ht'>test 1</span><span id='vt'>test 2</span></div>");

Now $htmlStr is a jQuery object, and you can manipulate it with the multitude of jQuery methods.

patrick dw
$('#ht', htmlStr).text() should be replace with $(htmlStr).find('#ht'). Since jQuery internally will do the exact same it's just one function call overhead with a terrible readability.
jAndy
Readability is in the eye of the beholder. :o)
patrick dw
performance is not.
jAndy
@jAndy: I don't understand your point. How does mine suffer a performance loss?
patrick dw
+1  A: 
var htmlStr = "<div><span id='ht'>test 1</span><span id='vt'>test 2</span></div>";
$(htmlStr).find('#ht').text();

should do it.

Kind Regards

--Andy

jAndy