17

I wonder if there is a way to convert string into jQuery object and select inner elements without injecting the whole string into DOM and manipulate it in there. Thanks.

If possible, please give me example of converting

<div id=a1></div>
<div id=a3></div>

And select a1 from the object variable.

2 Answers 2

26

This will create elements from the html and find the a1 element:

var element = $('<div id="a1"></div><div id="a3"></div>').filter('#a1').get(0);
Sign up to request clarification or add additional context in comments.

Comments

6

The correct way to do this is:

var a1 = $('<div id="a1"></div><div id="a3"></div>').filter('#a1')[0];

Getting the DOM element out with [0] is equivalent to .get(0).

Update: interesting, I've never come across this corner case before but this:

var a1 = $("#a1", "<div id=a1><//div><div id=a3><//div>")[0];

doesn't work when the element is at the top level, which I consider to be a bug. I've never come across that before so I thought I'd leave it up here as a cautionary tale. Thanks to Crescent Fresh for pointing that out.

1 Comment

No, what you have translates to $(<html>).find('#a1'), and find doesn't search top level elements in the set. @Guffa's filter answer does however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.