2
var span = '<span class="we w_o_r_d_s" id="we" contenteditable="false">we</span>' 

console.log(span.id);
console.log(span.attr('id'));
console.log(span.getAttribute('id'));

var div = document.createElement('div');
div.innerHTML = span;


console.log(div.id);
console.log(div.attr('id'));
console.log(div.getAttribute('id'));



//I want to log `we`

http://jsfiddle.net/3BTdk/1/

I looked here but couldn't get it. THanks.

Community
  • 1
  • 1
Squirrl
  • 3,870
  • 9
  • 41
  • 75

5 Answers5

2

Create a jQuery object and use .attr('id') to get the id.

var span = '<span class="we w_o_r_d_s" id="we" contenteditable="false">we</span>'; 
var id = $(span).attr('id');

The demo.

Without jQuery version:

var tmp = document.createElement('p'); 
tmp.innerHTML=span;
console.log(tmp.childNodes[0].id);

And the demo.

xdazz
  • 149,740
  • 33
  • 229
  • 258
1

You can use jQuery function to convert the string to jQuery object. It will allow you to apply jQuery selectors / functions on it.

Live Demo

var span = jQuery ('<span class="we w_o_r_d_s" id="we" contenteditable="false">we</span>');
var id = span.attr('id');
Adil
  • 139,325
  • 23
  • 196
  • 197
1

if page has just one span

then var id = $('span').attr('id');

http://jsfiddle.net/Vinay199129/3BTdk/3/

Vinay Pratap Singh
  • 9,193
  • 3
  • 23
  • 49
1

instead of span.attr('id') use $(span).attr('id')

The reason you might want to wrap jQuery/$ functionality around a DOM element should be obvious. Doing so gives you the ability to use jQuery chaining, should you have need for it.

Rakesh Kumar
  • 2,648
  • 1
  • 14
  • 32
0

See your fiddle which I updated...

Or use this:

console.log($(span).attr('id'));
Furquan Khan
  • 1,536
  • 1
  • 13
  • 30