I always thought that input
elements are prohibited of having DOM contents, as stated here (at 'Permitted content') and here (in 'Tips and Notes').
Now I'm working in a project where several different input element types are rendered and altered in javascript (eg plain input
text-elements and select
). In that altering process, a hidden input
is placed inside those elements, holding the current selected value.
So apparently it is possible via jQuery to add an input
element into another input element (and using it afterwards):
function doIt() {
//clear children of parent input
$('#parentInput').children().remove();
//create new input and append it to the parent input
$('<input>').attr({
type: 'hidden',
id: 'testInput',
value: 'Test value inserted into nested test input'
}).appendTo($('#parentInput'));
//get value of new nested input and write it to output div
$('#output').html($('#testInput').val());
}
$('#doIt').on('click', doIt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="Test" id="parentInput">
<button id="doIt">Do it</button>
<div id="output"></div>
or even a div
:
function doIt() {
//clear children of parent input
$('#parentInput').children().remove();
//create new input and append it to the parent input
$('<div id="testDiv">Test value inserted into nested test div</div>').appendTo($('#parentInput'));
//get value of new nested input and write it to output div
$('#output').html($('#testDiv').html());
}
$('#doIt').on('click', doIt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="Test" id="parentInput">
<button id="doIt">Do it</button>
<div id="output"></div>
My question now is: Why is that possbile via jQuery (and thus via plain javascript, as jQuery is 'just' a wrapper), when input
elements are not supposed to have DOM content?
答案 0 :(得分:0)
某些浏览器可能(或可能不)支持W3C / HTML规范中未特别支持的行为。通常,您希望避开这些“功能”,因为它们在不同的浏览器中可能无法正常工作,或者更糟糕的是,浏览器修补程序可能会完全改变或破坏其行为,因为它们没有记录。
答案 1 :(得分:0)
我一直认为输入元素被禁止使用DOM内容,如此处所述(在“允许的内容”中)和此处(在“提示和注释”中)。
您混淆了HTML和DOM。 HTML只是文字。 DOM是浏览器根据该文本创建的内容。
以下是HTML。它无效,浏览器不会从中创建嵌套节点:
<input type="text" value="Test" id="parentInput">
<div id="testDiv">Test value inserted into nested test div</div>
</input>
浏览器创建的DOM树很可能看起来像是来自这个HTML:
<input type="text" value="Test" id="parentInput">
<div id="testDiv">Test value inserted into nested test div</div>
结束标记被忽略。浏览器在解析HTML时很宽容。
如果你像你一样直接操作DOM,那么浏览器没有理由阻止它。当呈现DOM时,浏览器知道如何呈现输入。它并不关心输入节点是否有子节点。它完全被忽略了。