2014-03-13 19 views
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/如何獲取表示爲字符串的範圍內的id?

我看着here但無法得到它。謝謝。

回答

2

創建一個jQuery對象,並使用.attr('id')獲得ID。

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

The demo.

沒有jQuery的版本:

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

And the demo.

1

您可以使用jQuery函數將字符串轉換爲jQuery對象。它可以讓你申請jQueryselectors/functions就可以了。

Live Demo

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

代替span.attr('id')使用$(span).attr('id')

的原因,你可能要環繞DOM元素jQuery/$功能應該是 明顯。這樣做可以讓你有能力使用jQuery鏈接,如果你有需要的話。

0

請參閱fiddle我更新中...

或者使用:

console.log($(span).attr('id')); 
相關問題