user3417601
user3417601

Reputation: 135

Get Id from HTML by means of Regular-Expression

How can I test, whether the Id of an object (e.g. Image , Div or Table ...) is in html-code. The ID could be e.g. as follows: id=My_Img_Id or id="My_Img_Id" or id = " My_Img_Id " or id = My_Img_Id

var sHTML = '... any Text abc < IMG src="path/myfile.jpg" id="My_Img_Id" style="..." > ... any Text';
var sId = 'My_Img_Id';
var sReg = '<.*? *id*\= *\"*['+sId+' *"*]$.*';
var sRegExp = new RegExp(sReg, "g");
var Result = sRegExp.test( sHTML );
alert( Result );

Many thanks in advance.

Upvotes: 1

Views: 122

Answers (2)

Adil
Adil

Reputation: 148150

First convert the html string to jQuery object then you can use find to get the element from jQuery object. Use the length property if it more then zero then the element with id exists in html string.

Live Demo

$(sHTML).find('#' +sId ).length

Upvotes: 2

Dhaval Panchal
Dhaval Panchal

Reputation: 648

try this

if ($(sHTML).find('#My_Img_Id').length) {
    //write your code here
}

Upvotes: 1

Related Questions