طريقة setAttribute() الخاصة بـ XML DOM

تعريف والاستخدام

setAttribute() الطريقة لاضافة خاصية جديدة.

إذا كانت هناك خاصية同名 موجودة في العنصر، فإنها تغير قيمتها إلى قيمة قيمة المتغيرات.

النص

elementNode.setAttribute(اسم,قيمة)
المتغيرات وصف
اسم مطلوب. يحدد اسم الخاصية التي يتم تعيينها.
قيمة مطلوب. يحدد القيمة التي يتم تعيين الخاصية إليها.

مثال

مثال 1

الكود التالي يحمّل "books.xml" إلى xmlDoc ويضيف خاصية "edition" لكل عناصر <book>:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
       myFunction(this);
   }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
    var x, i, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName('title');
    // اضافة خاصية جديدة لكل عنصر title
    for (i = 0; i < x.length; i++) {
        x[i].setAttribute("edition", "first");
    }
    // اخراج قيمة title و edition
    for (i = 0; i < x.length; i++) {
        txt += x[i].childNodes[0].nodeValue +
        " - Edition: " +
        x[i].getAttribute('edition') + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}

جرب بنفسك

مثال 2

من خلال استخدام setAttribute() تعديل قيمة الخاصية:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this);
    }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
    var x, i, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName('book');
    for (i = 0; i < x.length; i++) { 
        x.item(i).setAttribute("category", "BESTSELLER");  
    }
    // إخراج جميع القيم الخاصية
    for (i = 0; i < x.length; i++) { 
        txt += x[i].getAttribute('category') + "<br>";
    }
    document.getElementById("demo").innerHTML = txt; 
}

جرب بنفسك