We help IT Professionals succeed at work.

Sort through html in a string

impressionexpress
on
The following is the code I use to find what Im looking for in actual HTML
		var dataArray = new Array();
		$('.info_byrequests').each(function(){
			var appId = $(this).attr('data-appId');
			if(jQuery.inArray(appId, dataArray) == -1){
				dataArray.push(appId);
			}
		});	

Open in new window


However, now I need to do the same thing with HTML in a string
        get_applications().done(function(value) {
			var html_string = value;
                        // sort and compare results with actual HTML
			$('#list_app').html(html_string);
        });	

Open in new window

Comment
Watch Question

Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
you can pass HTML directly to jQuery and then query it
var html = '<div><p id="abc">We want this one</p><p>We don\'t want this one</p></div>';
var jq = $(html);
var found = jq.find('#abc');
console.log(found);

Open in new window

In your case it is not clear what you want to do with the string - if you could explain a bit more I can better advise you.

The above code demonstrates how to use an HTML string in the same way you would an HTML document using jQuery.

Author

Commented:
This is my html string I get from an ajax call
echo "<div data-appId=\"" . $result[ 'application_id' ] . "\" class=\"form_title info_byrequests date\">" . str_replace( " ", "-", $result[ 'app_date' ] ) . "</div>";

Open in new window


I need to search for every instance of data-appId=(Number compared by in javascript array) since there will be many and remove the intire div before displaying html to screen
			for(var i=0; i<=dataArray.length; i++){
			//	console.log('ID: ' + dataArray[i]);

			}

Open in new window

Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
Still not clear on what you are asking.
I need to search for every instance of data-appId
This is straight forward - find all <div> that has a custom data attribute appId
Number compared by in javascript array
Not sure what you mean here
remove the intire div before displaying html to screen
Which entire div? Based on what criteria.

Can you fill in the gaps as what you have explained does not give the full picture.

In the meantime consider this example

var html = '<div data-appId="123" class="form_title info_byrequests date">20200101</div><div></div><div></div>';
var jq = $(html);
jq.each(function(index, value) {
  if (value.dataset.appid) {
   // this element has a data-appId value
  }
})

Open in new window

Author

Commented:
The entire html string in PHP
		echo "<div data-appId=\"" . $result[ 'application_id' ] . "\" class=\"form_title info_byrequests date\">" . str_replace( " ", "-", $result[ 'app_date' ] ) . "</div>" . chr(13);
		echo "<div data-appId=\"" . $result[ 'application_id' ] . "\" class=\"form_title info_byrequests appNumber\">" . str_replace( " ", "", $result[ 'app_date' ] ) . "-" . $result[ 'application_id' ] . "</div>";
		echo "<div data-appId=\"" . $result[ 'application_id' ] . "\" class=\"form_title info_byrequests name\">" . strtoupper($result[ 'last_name' ] . ", " . $result[ 'first_name' ]) . "</div>";
		echo "<div data-appId=\"" . $result[ 'application_id' ] . "\" class=\"form_title info_byrequests phone\"><span class=\"telephone\">" . $result[ 'telephone' ] . "</span></div>";
		echo "<div data-appId=\"" . $result[ 'application_id' ] . "\" class=\"form_title info_byrequests creditType\">" . $result[ 'credit_type' ] . "</div>";
		echo "<div data-appId=\"" . $result[ 'application_id' ] . "\" class=\"form_title info_byrequests creditAmount\"><span class=\"dollar_sign\">$</span><span class=\"requested_credit\">" . $result[ 'credit_amount' ] . "</span></div>";
		echo "<div data-appId=\"" . $result[ 'application_id' ] . "\" class=\"form_title info_byrequests status\"><i class=\"" . $result[ 'class' ] . "\" title=\"" . $result[ 'status_name' ] . "\"></i></div>";

		echo "<div class=\"clear_all\"></div>";

Open in new window

lets say I have a javascript array as follows
var dataArray = new Array("55", "56", "57");

Open in new window

As you can see there are many div's with data-appId that will have the same value. the data value is compared with data already displayed to screen. to avoid duplicates, I want to remove all the div's that have data-appId=55 & 56 & 57 (as seen in the array) before I append the html string to the current html
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
Where does the array come from?
Do you need to progressively update it  - or is it fixed with those numbers?

My last post shows how to iterate over the content - you can easily add your code to do the array check. I can provide code but I need to understand exactly what the landscape is.

As you can see there are many div's with data-appId that will have the same value.
I can't see - there is no data that shows this.

You have not explained where the Array comes from - nor have you explained what must happen.

for instance - if the data received from the AJAX call contains the appId's 10,11,12,13 and you already have 10 and 11 showing - you only want to show 12 and 13? So we check each incoming appId against the array - if we find one that does not match - we then add that to the screen - AND then update the array with this id?

If you could clarify that bit for me please.

Author

Commented:
This is where the array comes from, The following code is inside function populate_applications()
                // determine what data we already have
		var dataArray = new Array();
		$('.info_byrequests').each(function(){
			var appId = $(this).attr('data-appId');
			if(jQuery.inArray(appId, dataArray) == -1){
				dataArray.push(appId);
			}
		});	

	setInterval(function() {
		populate_applications();
	//	console.log('Update');
	}, 5000);

Open in new window

Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
You did not answer my other questions?

This is taking much longer than it should - if you could just read my posts and answer my questions we can wrap this up.

So far I have given you everything you need to solve this problem - but if you want a complete solution I need to understand the problem space properly.

Author

Commented:
Which questions are you looking for me to answer ?
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
nor have you explained what must happen.

for instance - if the data received from the AJAX call contains the appId's 10,11,12,13 and you already have 10 and 11 showing - you only want to show 12 and 13? So we check each incoming appId against the array - if we find one that does not match - we then add that to the screen - AND then update the array with this id?

Author

Commented:
Yes, Julian. that's exactly what needs to happen.

what I tried before was clearing the div and repopulating which causes a sort of flash on update. this is annoying. Im looking for a smooth solution.
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
This has gone a bit stale so I need to get on top of what the issue is.

You are getting some HTML by AJAX.
You need to parse the HTML and extract items from the HTML and add them to the page but only if they are unique.

Is the page rendered with items OR area all items progressively added with AJAX calls - need to know if we must pre-populate the array on page load or if we can start with [] and then add to it with each AJAX?

Author

Commented:
Im getting HTML by AJAX
I need to add the HTML to the page only if its unique

When you land on the page at first, it will display all the proper results however, if there are records added to the database while on that page, it should append that added record
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
When you land on the page at first, it will display all the proper results
How do the id's from those results get into the array?

Author

Commented:
I create the array and add all the id's
Most Valuable Expert 2017
Distinguished Expert 2019
Commented:
I have put together a sample for this. Personally I would not use an array - but rather query the document directly to see if HTML must be added or not

This is my sample HTML. I have put the existing (on page) items in a container so it is easy to add to them.
When we query the server we only want to add items that don't have appIds in the set [124,125,126,127]
<div id="appIds">
  <div data-appId="124" class="form_title info_byrequests date">2020-01-15</div>
  <div data-appId="125" class="form_title info_byrequests date">2020-01-16</div>
  <div data-appId="126" class="form_title info_byrequests date">2020-01-17</div>
  <div data-appId="127" class="form_title info_byrequests date">2020-01-19</div>
</div>
<!-- A simple button to test the fetch -->
<button id="fetchNew">Fetch New</button>

Open in new window


Here is the JavaScript to do the rest

$(function() {
  // Global reference to the container where we will add items
  var container = document.getElementById('appIds');

  // Simulate fetching data using a button click
  $('#fetchNew').click(function(e) {
    e.preventDefault();

    // Fetch the data from the service
    $.post('t3792.txt', {}, function(html) {

      // Parse the HTML into a jQuery object. We prepend and append <div> tags so that we can enumerate items
      // returned and use the .find() function to extract those with data-appId attributes set
      var els = $('<div>' + html + '</div>').find('div');

      // iterate over the items found
      els.each(function(i,e) {

        // Check to see if this item is already in the document and if it is not append it
        if ($('div[data-appId=' + e.dataset.appid + ']').length === 0) {
          container.appendChild(e);
        } else {
          console.log(e, 'Already exists in document');
        }
      });
    });
  });
});

Open in new window


Working sample here