JQuery: how to extract text from a specific element in a variable

I have a variable containing simple HTML, similar to the following example: the contents of the variable are generated dynamically through Ajax:

var errors = "<span id='id1'>Value 1</span><span id='id2'>Value 2</span><span id='id3'>Value 3</span><span id='id4'>Value 4</span><span id='id5'>Value 5</span>"; 

How can I get the text of a specific element by its identifier in this variable , for example. span text with ID = ' id3 '? Here the result should be " Value 3 ".

I tried the following, but the result I get is always either an empty string or " [object Object] ":

  • $(errors).filter('#id3')
  • $(errors).filter('#id3').text()
  • $(errors).find('#id3').text()

Update:
After reading the comments and answers on this question, I broke my code and it seems that the problem is related to the successful part of Ajax, where data contains what I showed in the above example, but it looks like it is not stored in the " errors " variable. (If I hardcode a variable, then it works with .filter.)

 var errors = ''; $.ajax({ type: "post", url: "ajax.php", cache: "false", data: { node: 'fetchErrors', selectedLang: selectedLang }, success: function(data){ errors = data; } }); 

Can someone help me?

Thanks a lot in advance, Mike

+5
source share
4 answers

This works for me ( fiddle ).

 success: function(data){ var result = $(data).filter("#id3").text(); } 
+2
source

You were on the right track ...

 var errors = "<span id='id1'>Value 1</span><span id='id2'>Value 2</span><span id='id3'>Value 3</span><span id='id4'>Value 4</span><span id='id5'>Value 5</span>"; var obj = $(errors); var filter = $(obj).filter('#id3'); console.log(filter.text()); 

jsfiddle: fiddle

+4
source

try adding async: false to the ajax properties.

+2
source

This task:

 $(errors).filter("#id3").text() 
+1
source

All Articles