javascript - innerHTML in DOM -
i unable change text inside 'p' tag using script
<script> var firstitem = document.getelementbytagname('p'); firstitem.innerhtml = 'adding javascript'; </script>
you have several coding errors. here's corrected code:
<script> var firstitem = document.getelementsbytagname('p')[0]; firstitem.innerhtml = 'adding javascript'; </script>
the correct method
document.getelementsbytagname('p')
. note "s" @ end of "elements".then, because
document.getelementsbytagname('p')
returns html collection object, have either iterate on collection or reach collection grab specific dom object (which did in example[0]
).
and here's working code snippet:
// change first <p> tag document.getelementbyid("test1").addeventlistener("click", function(e) { var firstitem = document.getelementsbytagname('p')[0]; firstitem.innerhtml = 'adding javascript'; }); // change <p> tags document.getelementbyid("test2").addeventlistener("click", function(e) { var items = document.getelementsbytagname('p'); (var = 0; < items.length; i++) { items[i].innerhtml = 'setting items'; } });
<button id="test1">change text of first item</button><br><br> <button id="test2">change text of items</button><br><br> <p>this text</p> <p>this more text</p> <p>this , more text</p>
Comments
Post a Comment