關於元素節點的各種操作(attributes)

2021-10-04 19:39:05 字數 2205 閱讀 6807

在日常使用的過程中,getattribute、setattribute、removeattribute都是會用到的來操作元素的特性的一些方法,例如getattribute可以用來獲取元素的特性,那麼這跟直接獲取元素特性有什麼區別呢?

這裡先有這麼一串**

div

>

這時候,如果想要獲取該div元素上面的各種特性,有兩種方法。

第一種:

var myid = document.

getelementbyid

("myid");

console.

log(myid.

getattribute

("id"))

;console.

log(myid.

getattribute

("class"))

;console.

log(myid.

getattribute

("title"))

;console.

log(myid.

getattribute

("lang"))

;

第二種:

console.

log(myid.id)

;console.

log(myid.classname)

;console.

log(myid.title)

;console.

log(myid.lang)

;

這時候列印出來的數值都是一樣的

那麼這兩種方式都一樣,官方沒理由不刪了其中一種的,可是當我們換種方式來測試

div

>

這時候再來一次

console.

log(myid.onclick)

;console.

log(myid.

getattribute

("onclick"

))

列印出來的結果會變成這樣出現這種情況的主要元嬰是onclick以及其它的一些事件處理程式屬性本身就應該是被賦予為乙個函式值,也就是乙個第一種結果,而通過getattribute獲得的則會變成相對應的字串。

那麼在什麼情況下需要使用getattribute呢??

這裡來看一下這個情況

div

>

然後我們想要列印這條xuedinge的時候,兩種方法出現這樣的情況。

console.

log(myid.xuedinge)

;console.

log(myid.

getattribute

("xuedinge"

))

也就是說,在需要獲得元素自定義的特性的時候,就需要使用getattribute,可是如果是本身固有的,則推薦第一種方式。

這種屬性是依託於element型別的一種查詢方式

console.

log(myid.attributes[

"id"

].nodevalue)

這裡同樣也可以得出id的值,那麼這種方式有什麼作用的。

例如:當乙個元素裡面有很多種特性,我們需要遍歷這些特性的時候,也就是當需要將dom結構序列化為html字串的時候,這種時候就是attributes的使用場景了。

例如:

div

>

然後我們需要把裡面的特性全部拿出來串聯成字串

var myid = document.

getelementbyid

("myid");

function outattributes

(element)

return pairs.

join(""

);};

console.

log(

outattributes

(myid)

);

我是乙隻會切圖的老狗,剛剛開始寫部落格,求點贊!!!

jquery 操作各種元素

獲取選中的值 獲取一組radio被選中項的值 var item input name items checked val 獲取select被選中項的文字 var item select name items option selected text select下拉框的第二個元素為當前選中值 sel...

jQuery對元素 節點的操作

一 文字內容的操作 方法 text text val 例子 div div 獲取 div元素 console.log div.text 獲取文字內容 div.text aaaaa 設定了文字的內容 二 html內容的操作 html 用於獲取第乙個匹配元素的 html 內容 html val 用於設定...

關於時間的各種操作

日期字串格式大小比較 string str1 2015 02 08 string str2 2015 01 08 int res str1.compareto str2 1是大於 0是等於 1是小於獲取某年第一天日期 calendar calendar calendar.getinstance ca...