javascript - .prop() vs .attr()

Mots clés : javascriptjquerydomattrpropjavascript

meilleur 4 Réponses javascript - .prop() vs .attr()

vote vote

97

<input id="cb" type="checkbox" checked> <input id="cb" type="checkbox" checked="checked"> 
vote vote

89

<a href='foo.html' class='test one' name='fooAnchor' id='fooAnchor'>Hi</a> 
 +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |             HTMLAnchorElement             | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | href:       "http://example.com/foo.html" | | name:       "fooAnchor"                   | | id:         "fooAnchor"                   | | className:  "test one"                    | | attributes:                               | |    href:  "foo.html"                      | |    name:  "fooAnchor"                     | |    id:    "fooAnchor"                     | |    class: "test one"                      | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ 
var link = document.getElementById('fooAnchor'); alert(link.href);                 // alerts "http://example.com/foo.html" alert(link.getAttribute("href")); // alerts "foo.html" 
vote vote

78

var attr; attr = document.body.getAttribute("class"); //IE 8 Quirks and below attr = document.body.getAttribute("className"); 
vote vote

65

<input blah="hello"> 
$('input').attr('blah', 'apple'); $('input').prop('blah', 'pear'); 
<input style="font:arial;"/> 
<input value="hello" type="text"/>     $('input').prop('value', 'i changed the value'); 

Questions similaires