0

I'm trying to extract data from a JS function that only renders an element's HTML - and I need the element's ID or class.

Example:

JS Element Value:
x = '<div class="active introjs-showElement introjs-relativePosition" id="myId">Toate (75)</div>';

I need to do get the element's id or class (in this case the id would be myId).

Is there any way to do this? Strip the tags or extract the text via strstr?

Thank you

Crys Ex
  • 335
  • 1
  • 4
  • 9
  • yes, you can use regex for this. http://stackoverflow.com/questions/16559171/regular-expression-to-get-a-class-name-from-html – vaso123 Oct 22 '14 at 09:58
  • Regex is overkill, even if he chooses not to use jQuery. –  Oct 22 '14 at 10:07

2 Answers2

2

The easiest thing to do would be to grab the jQuery object of the string you have:

$(x);

Now you have access to all the jQuery extensions on it to allow you to get/set what you need:

$(x).attr('id'); // == 'myId'

NOTE: This is obviously based on the assumption you have jQuery to use. If you don't, then the second part of my answer is - get jQuery, it's designed to make operations like these very easy and tackle compatibility issues where it can too

0

You may want to take a look at this:

var div = document.createElement('div');
div.innerHTML = '<div class="active introjs-showElement introjs-relativePosition" id="myId">Toate (75)</div>';
console.log(div.firstChild.className);
console.log(div.firstChild.id);
tgogos
  • 23,218
  • 20
  • 96
  • 128