简体   繁体   中英

How to access the fields of Elements in HTML DOM by Javascript?

I am new to HTML DOM operations. I failed even for simple examples.

Here are my codes:

<h1>head 1</h1>
<h2>head 2</h2>
<script type="text/javascript">
var h1 = document.getElementsByTagName('h1');
alert("tagName : "+h1.getTagName());
h1.parentNode.removeChild(h1);
</script>
<h3>head 3</h3>

The above codes even don't pop out any "alert".

I also tried:

alert("nodeType: "+h1.nodeType);
alert("nodeName: "+h1.nodeName);
alert("nodeValue: "+h1.nodeValue);
alert("tagName: "+h1.tagName);

However, they all response undefined .

You forgot quotes around your parameter:

var h1 = document.getElementsByTagName(h1);

should be:

var h1 = document.getElementsByTagName('h1');

Do you use Firebug ? If not you should. It would let you know you had this error.

This site is really useful. http://www.w3schools.com/jsref/dom_obj_node.asp

Once you get a grasp of it, be sure to use jquery or some other library for working with dom (makes life easier): http://jquery.com/

<h1>head 1</h1>
<h2>head 2</h2>
<script type="text/javascript">
var h1 = document.getElementsByTagName('h1')[0];
alert("tagName : "+h1.localName);
h1.parentNode.removeChild(h1);
</script>
<h3>head 3</h3>

it should be:

var h1 = document.getElementsByTagName('h1')[0];

Explanation:

Whenever you use getElements... (note the s) you actually get an array. by using [0] after the var h1 = document.getElementsByTagName('h1') it actually means get me the first element with TagName = 'h1'

you other options are either to loop on this array and then use h1[i] (for example) or to choose the proper member of this array when it actually being used like so -

alert("tag name: ",h1[0]);

just for comparison, when you use getElementById you get only one element and therefore you can use it directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM