botenvouwer
botenvouwer

Reputation: 4432

.each trough html inside variable

He I am just asking how to use .each when my html is inside java-script variable and not in the DOM itself.

If I have html like this:

<html>
    <h1>deze</h1>
    <h1>this</h1>
    <h1>dies</h1>
</html>

I can do:

$('h1').each(function(){
    var test = $(this).html();
    alert(test);                
});

It will just give a alert 3 times telling deze, this, dies. Now I want to do the same but then with html inside variable. No idea how this is my pseudo code:

var html = '
           <h1>deze</h1>
           <h1>this</h1>
           <h1>dies</h1>
           ';

$(html).each('h1', function(){
    var test = $(this).html();
    alert(test);                
});

Not sure how to do this I have no idea. Please enlighten me!

Upvotes: 1

Views: 207

Answers (4)

Hurricane Hamilton
Hurricane Hamilton

Reputation: 574

Try this out to parse your sting into some DOM nodes first: http://api.jquery.com/jQuery.parseHTML/

var html = '<div>\
           <h1>deze</h1>\
           <h1>this</h1>\
           <h1>dies</h1>\
           </div>';
var test = $.parseHTML(html);

$('h1',test).each(function(){
    var test = $(this).html();
    alert(test);                
});

example here: http://jsfiddle.net/cnWqQ/3/

Also, in your question I noticed that your html variable won't parse into a variable the way it is typed onto multiple lines.

One thing to watch out for when using this method is that it won't work if the element that you are searching for is at the top level. to avoid this, just wrap your string in a div. for more info on this see here: http://fredwu.me/post/554746690/jquery-tip-traverse-parse-html-string

Upvotes: 2

Roko C. Buljan
Roko C. Buljan

Reputation: 206209

LIVE DEMO

var html = '<h1>deze</h1>'+
           '<h1>this</h1>'+
           '<h1>dies</h1>';

$(html).filter(function(){
    var test = $(this).html();
    alert(test);                          // deze // this // dies
});

Upvotes: 1

epascarello
epascarello

Reputation: 207531

var html = '\
           <h1>deze</h1>\
           <h1>this</h1>\
           <h1>dies</h1>\
           ';

$("<div/>").html(html).find("h1").each(function(){
    var test = $(this).html();
    alert(test);                
});


$(html).filter("h1").each(function(){
    var test = $(this).html();
    alert(test);                
});

Upvotes: 1

Ayman Safadi
Ayman Safadi

Reputation: 11552

Try something like:

$(html).filter('h1').each(function(){
    var test = $(this).html();
    alert(test);                
});

Fiddle: http://jsfiddle.net/m7f3F/

Upvotes: -2

Related Questions