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
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();