Reputation: 4941
How would loop through HTML stored in a variable for 'ul' tags? This is what I have so far but the alert() don't even trigger, Im a bit lost...
var data = 'HTML';
$('ul', data).each(function(i,v) {
var theTag = v.tagName;
var theElement = $(v);
var theValue = theElement.html();
alert(theTag+'\n'+theElement+'\n'+theValue);
});
Thanks
Upvotes: 3
Views: 4939
Reputation: 434965
You're trying to use the "selector, context" form of the $()
call:
jQuery( selector [, context] )
selector A string containing a selector expression
context A DOM Element, Document, or jQuery to use as context
A string of HTML doesn't match any of the things that context
is supposed to be so jQuery doesn't know what to do with your arguments and makes the wrong guess.
You probably want to do it like this:
$(data).filter('ul').each(function(i,v) {
//...
});
Demo: http://jsfiddle.net/ambiguous/gxGB8/
Or, if you don't know at what level the <ul>
elements will be, wrap the HTML in a <div>
and use find
instead of filter
:
$('<div>' + data + '</div>').find('ul').each(function(i, v) {
//...
});
Demo: http://jsfiddle.net/ambiguous/tM4ua/
Upvotes: 6
Reputation: 20487
Try this:
$('ul').each(function() {
// Gets underlying element object
var theElement = $(this).get(0);
var theTag = theElement.tagName;
// Can also use .text() if you want just the textual content
var theValue = $(this).html();
// theElement can't be printed, it's an object
alert(theTag+'\n'+theValue);
});
I am presuming here that you want the contents of a number of <ul>
tags, rather than the <li>
parts of a single list.
Upvotes: 0
Reputation: 888223
.val()
returns the value of a form input.
It doesn't work on arbitrary elements.
You want .text()
or .html()
.
EDIT: To find elements in an HTML string, you should write $(html).find('ul')
Upvotes: 2