lee shinwell lee shinwell - 5 months ago 14
Javascript Question

about jQuery html(), attr() and val()

I want to copy some DOM nodes by html() method. I use val() to modify the input value, then use html() to copy the input node, but the value of the copied input is old!! When I use attr() to modify the input value, then copy it by html(), it looks like RIGHT!

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>

<p id="con1"><input type="text" value="1"></p>
<p id="con2"></p>

<button onclick="doTest1()">test1</button>
<button onclick="doTest2()">test2</button>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
var doTest1 = function() {
$("#con1 > input").val("2");
$("#con2").html( $("#con1").html() );
};

var doTest2 = function() {
$("#con1 > input").attr("value","2");
$("#con2").html( $("#con1").html() );
};
</script>
</body>
</html>

Answer

jQuery implements .attr() and .val() like,

.attr(x, y) - element.setAttribute(x, y);

.val(x) - element.value = x;

When you copy the entire html after you set the value with .val(), you basically just copy the entire element with its value not updated as like,

<input type="text" value="1">

And that's why the value would still be 1.

By changing the value with .val() after page load, does not update the attribute value in your input. Even for the element above, if you run,

$('input').val('2'); // <input type="text" value="1">

But if you run with .attr(),

$('input').attr('2'); // <input type="text" value="2">

Note that .html() gets the exact HTML contents of the element.

Comments