2

I have problems to access elements of a html response of an ajax request. I am using jquery and I try to simplify the problem as much as possible:

I have an ajax html response like this (kept very simply):

<div id="div_1"><span id="span">Text in Span</span></div>
<div id="div_2">Text in div</div>

Now I am trying to access certain elements of this html response with jquery:

 $.ajaxSetup(
 {
   success: function(html)
   {
    alert($('#span', html).html()); //works fine
    alert($('#div_1', html).html()); // doesn't work, why?
    alert($('#div_2', html).html()); // also doesn't work
    alert( $('span', html).first().attr('id') ); // works fine
   }
 }

I actually want to get the id of the first div element, but i seems as i cannot access the first "level" of the html response. I probably could solve the problem with a div surrounding container, which contains everything else.

Is there a another solution oder could somebody explain me, why jquery seems to ignore the first level of the html?

Thank you very much and sorry for my english (I am not a native speaker) Phantom

0

3 Answers 3

1

Try wrapping response into div, put it in the variable and then use find() to get the element you need from response.

Hope, that helps.

Sign up to request clarification or add additional context in comments.

8 Comments

You don't need to add any markup; simply wrapping the response in jQuery, $(html) will parse the HTML and allow it to be searched/updated.
alert($('<div>first</div><div>second</div>').find('div:first').html()); try it.
alert($('<div><div>first</div><div>second</div></div>').find('div:first').html()); and try this one in your console.
Also, you can try this... alert($('<div id="first">first</div><div>second</div></div>').find('div#first').html()); So... :)
Upvoting this. Wrapping is relevant since providing jQuery with a context is equivalent of $(context).find(...), which means that only child nodes will be searched. Wrapping is not needed to make the HTML jQuery searchable, but in order to make the specified selector find the intended elements.
|
1

you should add hash for id selectors:

 $.ajaxSetup(
 {
   success: function(html)
   {
    alert($('#span', html).html()); 
    alert($('#div_1', html).html());  
    alert($('#div_2', html).html()); 
    alert( $('span', html).first().attr('id') ); 
   }
 }

1 Comment

Sorry, I have just made this mistake in the example - the problem occurs even if you add the hash. I corrected the example.
0

Ad the hast tag to the divs like this : #div_1 because its an id.

1 Comment

Sorry, I have just made this mistake in the example - the problem occurs even if you add the hash. I corrected the example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.