XML DOM روش item()
تعریف و استفاده
item()
مетод به بازگشت نود در مقادیر لیست نودها در موقعیت مشخصی میپردازد.
نحوهنویسی
item(index)
پارامتر | توضیح |
---|---|
index | نشانگر |
مثال
مثال 1
این کد "books.xml" را به xmlDoc بارگذاری میکند، دورهپیمایی از عناصر <book> و چاپ مقادیر ویژگی category را انجام میدهد:
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, att, xmlDoc, txt; xmlDoc = xml.responseXML; txt = ""; x = xmlDoc.getElementsByTagName('book'); for (i = 0; i < x.length; i++) { att = x.item(i).attributes.getNamedItem("category"); txt += att.value + "<br>"; } document.getElementById("demo").innerHTML = txt; }
مثال 2
دورهپیمایی از پروژههای لیست نودها:
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.documentElement.childNodes; for (i = 0; i < x.length; i++) { if (x.item(i).nodeType == 1) { txt += x.item(i).nodeName + "<br>"; } } document.getElementById("demo").innerHTML = txt; }
مثال 3
تغییر مقادیر پروژه:
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, attlist, att, xmlDoc, txt; xmlDoc = xml.responseXML; txt = ""; x = xmlDoc.getElementsByTagName("book"); // ویرایش مقادیر ویژگی attribute از property category for (i = 0; i < x.length; i++) { attlist = x.item(i).attributes; att = attlist.getNamedItem("category"); att.value = "بهترین فروشنده"; } // 输出所有 title 和 edition for (i = 0; i < x.length; i++) { txt += x[i].getAttribute("category") + "<br>"; } document.getElementById("demo").innerHTML = txt; }