开发者

Simple JQuery selector does not find ID within a string

var chk = "<div id='test'>Trying</div>";

    alert($("#test",chk).html());

Well this JQuery by String is not working its so simple but it doesn't work =/ What is it wrong in it ? thanks开发者_高级运维 in advance!


Try something like this:

var chk = "<div><span id='test'>Trying</span></div>";
alert($("#test",chk).html());

The first parameter "#test" is your selector (what you really want to get).

And the second parameter chk is your context (within your query / search is performed).


SunnyRed hit the nail on the head.

The trouble is that when you say:

$("#test",chk)

You are searching for all DOM elements within (and not including) the chk tag. Unfortunately because that tag contains #test, your search does not find anything. Consider the jQuery documentation:

By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function.

If you wrap your string with a root-level <div> and then try the search, you will get what you are after:

var chk = "<div><div id='test'>Trying</div></div>";
alert($("#test", chk).html());

For a live example, see: http://jsfiddle.net/GpdYz/


alert($(chk).html()); // Trying
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜