【javascript学习指南】JAVASCRIPT中document.getElementById使用方法

更新时间:2019-07-24    来源:网页配色    手机版     字体:

【www.bbyears.com--网页配色】

改变 HTML 属性

如需改变 HTML 元素的属性,请使用这个语法:

document.getElementById(id).attribute=new value
本例改变了  元素的 src 属性:



 
 
<script type="text/javascript">
document.getElementById("image").src="landscape.jpg";
</script>
改变 HTML 样式

如需改变 HTML 元素的样式,请使用这个语法:


document.getElementById(id).style.property=new style
下面的例子会改变

元素的样式:


Hello World!
 
<script type="text/javascript">
document.getElementById("p2").style.color="blue";
</script>

有人看到会说使用jquery $美元符号来代替document.getElementById是多好啊,下面我们也来看看

$("#a").val()

当然如果不想使用jquery插件包可以自定义$,如下

JavaScript可以定义$符号函数,简写或书写兼容性更好的代码。

代码如下:

function $(id){return document.getElementById(id); 

上面的关于新版本的浏览器都是没有成绩的,假如运用陈旧的浏览器,可以运用上面的函数
代码如下:
 
function $(objectId) {
if(document.getElementById && document.getElementById(objectId)) {
// W3C DOM
return document.getElementById(objectId);
}
else if (document.all && document.all(objectId)) {
// MSIE 4 DOM
return document.all(objectId);
}
else if (document.layers && document.layers[objectId]) {
// NN 4 DOM.. note: this won"t find nested layers
return document.layers[objectId];
}
else {
return false;
}
}

document.getElementById 框架中元素操作

[window.]parent.document.getElementById("button") //查找父页面中id为button的对象

parent.document.getElementById("frame").style.height-----即取得页面中的id名字为“frame”的元素,取得它的显示高度

function init(){
parent.document.getElementById("frame").style.height=document.body.scrollHeight;
}

补充:

从iframe中查找父页面中对象的方法:
  1.js
   
    [window.]parent //查找父页面的window对象 
    [window.]parent.document //查找父页面的document对象 
    [window.]parent.document.body //查找父页面的body对象 
    [window.]parent.document.getElementById("button") //查找父页面中id为button的对象 

  2.jquery
    $([window.]parent) //查找父页面的window对象 
    $([window.]parent.document) //查找父页面的document对象 
    $([window.]parent.document.body) //查找父页面的body对象 
    $([window.]parent.document.body).find("#button") //查找父页面中id为button的对象 
 
 
点击事件子页面控制父页面元素。
$(".demo_close").click(function () {
            $("#iframeIE", window.parent.document).hide();
  });  
 
 

从父页面中查找iframe子页面中对象的方法:
 1. JS代码:
  document.getElementById("iframe").contentWindow //查找iframe加载的页面的window对象 
  document.getElementById("iframe").contentWindow.document //查找iframe加载的页面的document对象 
  document.getElementById("iframe").contentWindow.document.body //查找iframe加载的页面的body对象 
  document.getElementById("iframe").contentWindow.document.getElementById("icontent") //查找iframe加载的页面的id为icontent的对象
 
 2.jQuery:
    $iframe.contents() //查找iframe加载的页面的document对象 
    $iframe.contents().find("body") //查找iframe加载的页面的body对象 
    $iframe.contents().find("body").find("#icontent") //查找iframe加载的页面的id为icontent的对象

本文来源:http://www.bbyears.com/wangyezhizuo/59433.html