2

The following code works fine:

function createElement(element) {
  var id = $(element).attr('id');//and do your stuff with the id
}
createElement('<div id="abc">Some content</div>');

But I wanted to with pure javascript like this:

function createElement(element) {
  var id = this.id;//returns undefined
  console.log(id);
}
createElement('<div id="abc">Some content</div>');

I also tried element.id but still results in undefined. So How can I get the id abc with pure javascript?


I also tried like this:

function createElement(element) {
  var htmlObject = document.createElement('div');
    htmlObject.innerHTML = element;
    var id = htmlObject.id;//and do your stuff with the id
    console.log(id);
}
createElement('<div id="abc">Some content</div>');

But returning (an empty string)

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231

2 Answers2

1

For newer browsers jQuery will use the DOMParser internally, and do something like this

function createElement(element) {
    var doc  = new DOMParser().parseFromString(element, "text/html");
    var elem = doc.body.firstChild;
    console.log(elem.id)
}

FIDDLE

This is the preferred way of doing this, using the built in parser, but it's not supported in IE8 and below, there you'd probably have to use innerHTML etc. so you'll have to add a fallback for DOMParser if old browsers are an issue.

adeneo
  • 312,895
  • 29
  • 395
  • 388
1

You were almost there:

function createElement(element) 
{
    var div = document.createElement('div');
    div.innerHTML = element;

    var id = div.firstChild.id; // use firstChild
    console.log(id);
}
createElement('<div id="abc">Some content</div>');

Demo

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309