Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - get text of html return

Tags:

jquery

dom

ajax

This is probably simple but i can't seem to find my answer...

i have an ajax call that returns html

 dataType: "html"

and it's returned 'msg' looks like:

<div id="x"><p>Hello</p></div>

and that gets dom-added to the top of a parent div:

ajax call...
request.done(function(msg) {
   $('#parent').prepend(msg);
}

The issue is, i DONT want to do this dom manipulation if it's text hasn't changed (as there are other effects that take place that i've truncated out. (This is a notice display that checks for updates in an interval)

so, what i want to do is find "Hello" within msg and compare it against a current div x's p that may already be on page. This second part is easy to address, but the first part, I need to do something like msg.text() to just get "Hello", but a few varities i tried failed.

pointers?

like image 638
BReal14 Avatar asked Mar 28 '13 18:03

BReal14


4 Answers

use filter() to find the text..

try this

$(msg).filter('div#x p').text(); //this  will give you hello

OR find()

 $(msg).find('div#x p').text();
like image 63
bipen Avatar answered Oct 24 '22 01:10

bipen


So you can do the following :

Hold the text from the previus query in a variable

var previusData;

then after the first request add that data to the variable, you can do this by using filter or like this :

previusData = $("#x p").html();

then before adding it to the DOM do a check by adding a new varible

request.done(function(msg) {
   var currData = $("#x p").html();
   if(currData != previusData){
     $('#parent').prepend(msg);
   }
}
like image 36
Georgi-it Avatar answered Oct 24 '22 00:10

Georgi-it


Assuming that the "notice" isn't present on page load and it gets fetched after page load, you could use a global variable (or a namespace) to hold previous value of the response and every time a new response is received, match it against the already stored response; discard if not changed; or use if changed and update the global variable

var cached_response = '';
ajax call...
request.done(function(msg) {
   if(msg != cached_response){
      $('#parent').prepend(msg);
      cached_response = msg;
   }
}
like image 1
Ejaz Avatar answered Oct 23 '22 23:10

Ejaz


One way is, you can use regex form replacing all html tags like this :

$(document).ready(function() {
    var text = '<div id="x"><p>Hello</p></div>';
    console.log(text.replace(/(<([^>]+)>)/ig,""));
});

Just put this line in your script, and compare with the data.

Here is the working example : http://jsfiddle.net/cGnG5/1/

And another way is using .filter() function as told in another answer.

like image 1
Nishu Tayal Avatar answered Oct 24 '22 00:10

Nishu Tayal