Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to extract text from specific element within variable

I have a variable that contains simple HTML looking like the following example - the content of the variable is generated dynamically via 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 ID within this variable, e.g. the text of span 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]":

  1. $(errors).filter('#id3')
  2. $(errors).filter('#id3').text()
  3. $(errors).find('#id3').text()

Update:
After reading through the comments and answers on this I split my code up and it seems the issue is with the success part of the Ajax where data contains what I showed in the example above but it seems it is not getting stored in the variable "errors". (If I hardcode the 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 with this ?

Many thanks in advance, Mike

like image 406
keewee279 Avatar asked Jul 04 '15 08:07

keewee279


4 Answers

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

like image 196
manta Avatar answered Nov 06 '22 19:11

manta


This works for me (fiddle).

success: function(data){
    var result = $(data).filter("#id3").text();
}
like image 41
Daniel Dušek Avatar answered Nov 06 '22 18:11

Daniel Dušek


try to add async: false to ajax properties.

like image 2
Konstantin Lyashenko Avatar answered Nov 06 '22 17:11

Konstantin Lyashenko


This does the job:

$(errors).filter("#id3").text()
like image 1
Antonio Smoljan Avatar answered Nov 06 '22 17:11

Antonio Smoljan