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]
":
$(errors).filter('#id3')
$(errors).filter('#id3').text()
$(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
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
This works for me (fiddle).
success: function(data){
var result = $(data).filter("#id3").text();
}
try to add async: false
to ajax properties.
This does the job:
$(errors).filter("#id3").text()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With