AKS
AKS

Reputation: 1279

Parsing html in innerHTML using javascript or jquery

How to get id and parse to get its number after getting the innerhtml like 3 examples below:-

var myIHTML = cell[0].innerHTML;

myIHTML = '<input type="submit" name="pic" value="Preview" /><div id="allItems1" style="display: none;"></div>' ;
or
myIHTML = '<input type="submit" name="pic" value="Preview" /><div id="allItems2" style="display: none;"></div>';
or
myIHTML ='<input type="submit" name="pic" value="Preview" /><div id="allItems11" style="display: none;"></div>'

I like to get the number from allItems id. like 1, 2, 11 etc.

Upvotes: 1

Views: 2149

Answers (2)

Sinan Guclu
Sinan Guclu

Reputation: 1087

You can use jQuery to parse the string:

var elems = $(myIHTML);

Then select the elements within using filter():

var alItems2Elem = elems.filter('#allItems2');

To get the number from the id of the div:

var alItemsId = elems.filter('div').attr('id').replace('allItems', '');

Here is a Codepen

Read more about .filter() here.

Upvotes: 0

metal03326
metal03326

Reputation: 1263

You can get your innerHTML back to DOM, so you can search in it and then parse the id. Here is an example:

// Create a div to insert back the contents into
var div = document.createElement('div');

// Insert the contents back
div.innerHTML = '<input type="submit" name="pic" value="Preview" /><div id="allItems1" style="display: none;"></div>';

// Get the element with id starting with allItems
var id = div.querySelector('[id^="allItems"]').id;

// Get the number by replacing non-digits with empty character and then converting the string to integer
console.log( 'Number from id is', parseInt( id.replace ( /[^\d.]/g, '' ) ) );

Upvotes: 2

Related Questions