简体   繁体   中英

Jquery not fetching 'h1' from text

I have this code

success: function(data) {
 title = $(data).find('h1').text();
alert(data);
alert(title);

}

Now data is showing all the html with h1 tags but title is showing null

If your data consists of something like:

<h1>heading</h1>
<p>content</p>

Then you need to wrap it before performing your queries:

var title = $('<div/>').html(data).find('h1').text();
alert(title);

The .find() method looks for descendant elements, so if your h1 element is at the "top" level it won't be found. Try .filter() instead:

title = $(data).filter('h1').text();

"Basically i want to grab the h1 and put in variable and then put the remaining html in data variable"

Given a data parameter that is a string something like this:

"<h1>My heading</h1><p>This is a test</p><p>This <span>is another</span> test.</p>"

You can do this:

var $data = $(data),
    $title = $data.filter("h1"),
    title = $title.text();

$data = $data.not($title);

The above results in two jQuery objects: $title , which contains the h1 element, and $data , which contains the rest. From there you can use $title.text() to get the actual text of the h1.

Simple demo: http://jsfiddle.net/yyKCW/

If you mean that you want the "remaining html" as a string then you can do the following after setting $data as above:

var restAsString = $("<div></div>").append($data).html();

Demo: http://jsfiddle.net/yyKCW/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM