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
  • 4,500
  • 9
  • 44
  • 79

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
  • 154,648
  • 35
  • 237
  • 264
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
  • 143,427
  • 25
  • 201
  • 198
1

if page has just one span

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

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

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,658
  • 1
  • 15
  • 33
0

See your fiddle which I updated...

Or use this:

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