HTML DOM replaceChild () الأسلوب
مثال
استبدل عقدة نصية في <li> عنصر في قائمة بعقدة نصية جديدة:
// Create a new text node called "Water"
var textnode = document.createTextNode("Water");
// Get the first child node of an <ul> element
var item = document.getElementById("myList").childNodes[0];
// Replace the first child node of <ul> with the newly created text node
item.replaceChild(textnode, item.childNodes[0]);
// Note: This example replaces only the Text node "Coffee" with a Text node "Water"
قبل الاستبدال:
- Coffee
- Tea
- Milk
بعد الاستبدال:
- Water
- Tea
- Milk
المزيد من الأمثلة "جربها بنفسك" أدناه.
التعريف والاستخدام
تستبدل طريقة replaceChild () العقدة الفرعية بعقدة جديدة.
يمكن أن تكون العقدة الجديدة عقدة موجودة في المستند ، أو يمكنك إنشاء عقدة جديدة.
نصيحة: استخدم طريقة removeChild () لإزالة عقدة فرعية من عنصر.
دعم المتصفح
Method | |||||
---|---|---|---|---|---|
replaceChild() | Yes | Yes | Yes | Yes | Yes |
بناء الجملة
node.replaceChild(newnode, oldnode)
قيمه المعامل
Parameter | Type | Description |
---|---|---|
newnode | Node object | Required. The node object you want to insert |
oldnode | Node object | Required. The node object you want to remove |
تفاصيل تقنية
قيمة الإرجاع: | كائن عقدة يمثل العقدة المستبدلة |
---|---|
إصدار DOM | كائن عقدة المستوى 1 الأساسي |
مزيد من الأمثلة
مثال
استبدل عنصر <li> في قائمة بعنصر <li> جديد:
// Create a new <li> element
var elmnt = document.createElement("li");
// Create a new text node called "Water"
var textnode = document.createTextNode("Water");
// Append the text node to <li>
elmnt.appendChild(textnode);
// Get the <ul> element with id="myList"
var item = document.getElementById("myList");
// Replace the first child node (<li> with index 0) in <ul> with the newly created <li> element
item.replaceChild(elmnt, item.childNodes[0]);
// Note: This example replaces the entire <li> element
قبل الإزالة:
- Coffee
- Tea
- Milk
بعد الإزالة:
- Water
- Tea
- Milk