简体   繁体   中英

Jquery selectors on ajax response

I receive ajax response as html, and I need to extract content of specified div.

It works:

function callback(data) {
    container = $(data).filter('div.container#container');
    container_in = $(container.html()).filter('div.container-in');
    main_container = $(container_in.html()).filter('div#main-container.main-container');
    div_content = $(main_container.html()).filter('div#content.right-block');
}

and it return empty

$(data).filter('div#content.right-block')

Can I use one selector on $(data) however?

function callback(data) {
    container = $(data).find('#container');
    container_in = container.find('div.container-in');
    main_container = container_in.find('#main-container');
    div_content = main_container.find('#content');
}

You don't need to keep using .html() and $() , because the first $(data) parses everything into DOM elements. Also, extra tag and class qualifiers on ID selectors are redundant, since IDs are required to be unique.

You can also get to the content with a single selector:

div_content = $(data).find("#content");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM