使用javascript或jquery在innerHTML中解析html

时间:2016-08-11 13:11:12

标签: javascript jquery html

如何在获取内部HTML之后获取id和解析以获取其数字,如下面的3个例子: -

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>'

我想从allItems id中获取数字。像1,2,11等。

2 个答案:

答案 0 :(得分:2)

您可以将innerHTML恢复为DOM,这样您就可以搜索它然后解析ID。这是一个例子:

// 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, '' ) ) );

答案 1 :(得分:0)

您可以使用jQuery来解析字符串:

var elems = $(myIHTML);

然后使用filter()选择元素:

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

从div的id中获取数字:

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

这是Codepen

详细了解.filter() here