How can I get html <option> tag's content with jQuery
I have a easy select tag:
<select>
<option></option>
<option></option>
</select>
Then I want use jQuery get the option's content:
var s=$('select option');
for(var i=0;i<s.length;i++){
console.log(s[i]);
}
it would only show "<option>"
,without the content.
If I use console.log(s[i].html());
, it would tell me it is wrong.
So how can I get the content?
You don't need jQuery to get the text content.
An HTMLOptionElement
has a .text
property.
var s = $('select option');
for(var i = 0; i < s.length; i++) {
console.log(s[i].text);
}
Although if you want the .outerHTML
of the element (a little confused by your question), you could do this...
var s = $('select option');
for(var i = 0; i < s.length; i++) {
console.log(s[i].outerHTML);
}
...though this only recently became available in Firefox, so you could create a method to patch it...
function outerHTML(el) {
return el.outerHTML || document.createElement('div')
.appendChild(el.cloneNode(true))
.parentNode
.innerHTML;
}
...and use it like this...
var s = $('select option');
for(var i = 0; i < s.length; i++) {
console.log(outerHTML(s[i]));
}
假设'内容'是指选项的文本值,请尝试以下操作:
$("select option").each(function() {
console.log($(this).text());
});
使用text()方法提取元素的文本节点值
链接地址: http://www.djcxy.com/p/83080.html上一篇: 使用原型JS删除具有特定值的选项