Reputation: 353
I am new in Jquery having problem with identify a specific tag among an HTML string. My HTML string is :
<span id="name">myname</span>
<span id="familyname">mysurname</span>
<span id="telnum">mytelnum</span>
<span id="postcode">myPostCode</span>
<span id="email">[email protected]</span>
And what I want is having each span inner text in separated variable.
The expected outcome is:
var a = 'myname';
var b = 'mysurname';
var c = 'telnum';
var d = 'myPostCode';
var e = '[email protected]';
but in my code it sounds that the find function is not working! here is my code:
var myHtmlCode = '<span id="name"> myname</span> <span id="familyname">mysurname</span> <span id="telnum"> mytelnum</span><span id="postcode"> myPostCode</span><span id="email">[email protected]</span>';
var $temp = $(myHtmlCode).find('span').contents().each(function() {
alert(this.val());
});
any helps is appreciated....
Upvotes: 2
Views: 1931
Reputation: 353
I used following piece of code:
var $temp = $(myHtmlCode).each(function () {
if (this.id == "name") {
alert(this.innerHTML);
}
});
Upvotes: 0
Reputation: 382150
Don't call contents
, it's useless here, as you can call the text
function from the span
elements.
And if you want to be able to explore the parsed string, you must embed the spans in one top level element.
You can put the texts in an object like this :
var texts = {};
$('<div>'+myHtmlCode+'</div>').find('span')
.each(function(){ texts[this.id] = $(this).text() });
Then you can read a text as, for example, texts.name
.
Demonstration (open the console to see the texts
object).
Of course you could as well do it as global variables, that is using window.name
instead of texts.name
, but it's really recommended to avoid cluttering the global name space.
Upvotes: 3