views:

56

answers:

4

Hi All, in my js I have a var in which i have stored innerHTML. the var is having value something like

                <h2>headline</h2>
                <div>....</div>
                 ...........

Now I want to retrieve value of h2 tag..what I am doing is

           $(myvar).find("h2").text()

but its not working...what should be the exact syntax. EDIT:

                 alert(myvar)=<h2>headline</h2>
                               <div>....</div>

Thanks.

A: 

Find() returns a collection of nodes. Use first():

h2text = $(myvar).first("h2").text();
Sergei
You would be correct, except that text() at worst concats the text of each matched element, which means that his code should work. Something else is wrong here and we need more info.
Clint Tseng
I am using 1.3.2
Wondering
A: 

Change your HTML to something like this.

<div>
    <h2>headline</h2>
    <div>....</div>
</div>
ChaosPandion
cant do that :-(
Wondering
Can you see if it fixes your issue?
ChaosPandion
any other workaround?
Wondering
A: 

generally would make more sense to wrap the contents of your var in a div as proposed by ChaosPandion.

if that's not possible, you can try this...

<script>
  var myVar = '<h2 id="test">heading</h2><div>stuff</div>';
  var jVar = $(myVar);

  alert($(jVar.get(0)).text());
</script>
koss
+2  A: 

The find method will not work for this case, because it gets the descendants of each element in the current set of matched elements (the h2 and the div in your example).

You can simply use filter (available on jQuery 1.3.2):

var myvar ="<h2>headline</h2>" +
           "<div>....</div>";

alert($(myvar).filter('h2').text()); // headline

Check an example here.

CMS
worked :-) thanks a lot.
Wondering