DOM操作

1、获取内容:

三个简单实用的用于 DOM 操作的 jQuery 方法:
text() - 设置或返回所选元素的文本内容

<pre name="code" class="html">$("#btn1").click(function(){
  alert("Text: " + $("#test").text());
});

 

html() - 设置或返回所选元素的内容(包括 HTML 标记)

$("#btn2").click(function(){
  alert("HTML: " + $("#test").html());
});

val() - 设置或返回表单字段的值

$("#btn1").click(function(){
  alert("Value: " + $("#test").val());
});

2、获取属性:

$("button").click(function(){
  alert($("#w3s").attr("href"));
});

3、设置内容:

$("#btn1").click(function(){
  $("#test1").text("Hello world!");
});
$("#btn2").click(function(){
  $("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
  $("#test3").val("Dolly Duck");
});


4、设置属性:

$("button").click(function(){
  $("#w3s").attr("href","http://www.w3cschool.cc/jquery");
});


5、添加元素:

append() - 在被选元素的结尾插入内容

$("p").append("Some appended text.");


prepend() - 在被选元素的开头插入内容

$("p").prepend("Some prepended text.");


after() - 在被选元素之后插入内容

$("img").after("Some text after");


before() - 在被选元素之前插入内容

$("img").before("Some text before");


6、删除元素:
remove() - 删除被选元素(及其子元素)

$("#div1").remove();


empty() - 从被选元素中删除子元素

$("#div1").empty();


过滤删除:

$("p").remove(".italic");


7、获取并设置 CSS 类:

样式表:

.important
{
font-weight:bold;
font-size:xx-large;
}

.blue
{
color:blue;
}

addClass() - 向被选元素添加一个或多个类

$("button").click(function(){
  $("h1,h2,p").addClass("blue");
  $("div").addClass("important");
});

removeClass() - 从被选元素删除一个或多个类

$("button").click(function(){
  $("h1,h2,p").removeClass("blue");
});


toggleClass() - 对被选元素进行添加/删除类的切换操作

$("button").click(function(){
  $("h1,h2,p").toggleClass("blue");
});


css() - 设置或返回样式属性

$("p").css({"background-color":"yellow","font-size":"200%"});


8、尺寸:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值