JS method of getting elements
You can use the built-in object## The getElementById method on #document is used to obtain the element with the id attribute set on the page. What is obtained is an html object, and then it is assigned to a variable
<scripttype="text/javascript"> var op =document.getElementById('p1'); alert(op)弹出对话框 </script> <p id="p1">这是一个p元素</p>
Note:If Put the above piece of code into and an error will be reported
Solution Method:Computer loading<scripttype="text/javascript">
1.window.onload = function(){
2.var op = document.getElementById('p1');
}
</script>
<p id="p1">这是一个p元素</p>
Get By selecting a page element, you can operate the attributes of the page element. The operation of attributes includes reading and writing attributes.
Methods for operating attributes
1. "." Operation
2. "[ ]" operation
"class" attribute is written as "className"
with horizontal bars should be changed to camel case , for example: "font-size" should be changed to "style.fontSize"
<scripttype="text/javascript">
1.加载:window.onload =function(){
2.获取:var oInput = document.getElementById('input1');
2.获取:var oA = document.getElementById('link1');
3.//读取属性值
var sValue =oInput.value;
var sType =oInput.type;
var sName =oInput.name;
var sLinks = oA.href;
4.//写(设置)属性
oA.style.color = 'red';
oA.style.fontSize = sValue;
}
</script>
<inputtype="text" name="setsize" id="input1"value="20px"><a href="" id="link1">百度</a>
Get through [ ]
<scripttype="text/javascript">
1.加载:window.onload= function(){
2.获取:var oInput1 =document.getElementById('input1');
2.获取:var oInput2 =document.getElementById('input2');
2.获取:var
oA =document.getElementById('link1');
3.//读取属性
var sVal1 = oInput1.value;
var sVal2 = oInput2.value;
4.//写(设置)属性
// oA.style.val1 = val2; 没反应
oA.style[sVal1] = sVal2;
}
</script>
<inputtype="text" name="setattr" id="input1"value="fontSize">
<input type="text" name="setnum" id="input2"value="30px">
<a href="" id="link1">百度</a>
Through the innerHtml attribute of the acquired tagRead and write the content of the tag package
Read op .innerHtml
Write op.innerHTML = "New Content"
The above is the detailed content of Example analysis of JavaScript methods and attributes for obtaining elements. For more information, please follow other related articles on the PHP Chinese website!