简体   繁体   中英

Access or get the id's of divs returned by php in jquery

DESCRIPTION :

After some php work at the end,my php returns the following output to the jquery

<div id = "container1">
   <div id = "chicken1"></div>
   <div id = "soup1"></div>
</div>


<div id = "container2">
   <div id = "chicken2"></div>
   <div id = "soup2"></div>
</div>

and so on ...

Now in the jquery call back it gets lot of results. Now in jquery I want to get the id's of all the divs it recieved from the php. How can I do that.

Following Is The Code :

PHP

echo '<div id = "container1">
       <div id = "chicken1"></div>
       <div id = "soup1"></div>
    </div>


    <div id = "container2">
       <div id = "chicken2"></div>
       <div id = "soup2"></div>
    </div>';

JQUERY

$.post("../PHP/get_all_new_msgs_on_profile.php",{arr:data},function(result)
{
         //get the id's of the divs result has... 

});

Now the $(result) has the divs returned by the php how can I extract the id's of the divs from it ... PLease ignore any typing mistake . thanks :)

Find all the div in html, iterate them, get the id's

Example

$(result).find('div').each(function(index){
console.log($(this).prop('id'));
});

I assume your result variable holds the string

var result = '<div id = "container1"><div id = "chicken1"></div><div id = "soup1"></div></div><div id = "container2"><div id = "chicken2"></div>   <div id = "soup2"></div></div>';

var parser = new DOMParser();
var data = parser.parseFromString(result, "text/html");

var div = data.getElementsByTagName( 'div' );
var ids = [];

for( var i = 0; i < div.length; i++ ){
    ids.push( div[i].getAttribute('id') );
}

Array "ids" contains array of ids of the elements.

Here's the fiddle

To select element with partial attribute match use div[id^="container"] . To do so, you have to actually put that PHP output to DOM first, use function like .append($data) .

I think it's better to process data in PHP and return some structured data to jQuery callback (for example in JSON) and in js loop that data and wrap in some HTML.

[PHP]
echo json_encode(['itemId1' => ['someAttributes'], ...]);

[JS]
$.ajax({
   url: "../PHP/get_all_new_msgs_on_profile.php",
   dataType: 'json', // Will autoparse JSON!
   success: function(jsonArray){
       $.each(jsonArray, function(index, item){
           $('.parentWrapper').append(
               '<div id="container' + index + '" class="container">' + item.name + '</div>'
           );
       });

       $(document).on('click', '.container', function(){
          alert('Clicked on element');
       });

       //Do not use any return!
   }
});

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