I have a javascript variable which is returning as below;
var html = '<span id="GRID_7_2_1_1_e_4" style="left: 517px; top: 162px; height: 32px; display: block;">'
I want to get the id(GRID_7_2_1_1_e_4) of this html.
Could you help me?
I have a javascript variable which is returning as below;
var html = '<span id="GRID_7_2_1_1_e_4" style="left: 517px; top: 162px; height: 32px; display: block;">'
I want to get the id(GRID_7_2_1_1_e_4) of this html.
Could you help me?
It can be done with javascript regexp:
var html = '<span id="GRID_7_2_1_1_e_4" style="left: 517px; top: 162px; height: 32px; display: block;">';
var regex = /id="([^"]*)"/g;
var matches = regex.exec(html);
console.log(matches);
Do you have jQuery running in your app?
If so, than you can use:
var html = '<span id="GRID_7_2_1_1_e_4" style="left: 517px; top: 162px; height: 32px; display: block;">'
var id = $(html).attr('id');
Assuming you don't have jQuery, you can try this approach:
Note: This approach will only work if the supplied HTML string is valid. Also note that
idshould be unique. So if there are multiple elements with sameid, first element will be fetched.
Sample
var html = '<span id="GRID_7_2_1_1_e_4" style="left: 517px; top: 162px; height: 32px; display: block;">'
var div = document.createElement('div');
div.innerHTML = html;
var id = div.firstChild.id;
// or
// var id = div.firstChild.getAttribute('id')
console.log(id);
// This should return `null` as `div` is an in-memory element and will not be a part of DOM tree
console.log(document.getElementById('GRID_7_2_1_1_e_4'))
Check this, this is exact answer to your question using only html and javascript
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var html = '<span id="GRID_7_2_1_1_e_4" style="left: 517px; top: 162px; height: 32px; display: block;">'
var test = html.match(/id="(.*)" /);
alert (test[1]);
}
</script>
</body>
</html>
I Assume that you are not using the jQuery then in this case you can use DOM Praser.
In this case I am using the Object of DOM Parser and then i am using it to convert the string into HTML element. and after converting it. I am finding the id of the element by firstchilid.id assuming that span is your first element
var htmlString = '<span id="GRID_7_2_1_1_e_4" style="left: 517px; top: 162px; height: 32px; display: block;">'
parser = new DOMParser();
doc = parser.parseFromString(htmlString, "text/xml");
console.log(doc.firstChild.id);