簡體   English   中英

僅當子元素存在於父元素下時,如何才能刪除它?

[英]How can I remove a child element only if it exists under a parent?

如果子tarif存在於social_headermenu元素中,我需要刪除它,具體取決於屏幕的大小。 現在我有控制台錯誤:

未捕獲的 DOMException:無法在“節點”上執行“removeChild”:要刪除的節點不是該節點的子節點。

let tarif = document.createElement("li");
tarif.className = "tarif";
let anchor = document.createElement("a");
anchor.setAttribute('href', "#");
let tarif_text = document.createTextNode("Tarifs");
anchor.appendChild(tarif_text);
tarif.appendChild(anchor);
const social_header = $("#social-header")[0];
const menu = $("#menu")[0];

$(window).resize(function() {
  if ($(this).width() > 800) {
    social_header.insertBefore(tarif, social_header.children[0]);
    menu.removeChild(tarif);
  } else {
    menu.appendChild(tarif);
    social_header.removeChild(tarif);
  }
});

由於您已經在頁面中包含 jQuery ,因此您可以通過使用它在處理未定義的目標元素時不引發任何錯誤的模式來簡化您正在做的事情。

在這種情況下,使用prependTo()在必要時添加元素,然后find()在父元素中檢索它並remove()它。 請注意,jQuery 的remove()方法在空 object 上調用時不會拋出錯誤。

const $tarif = $('<li class="tarif"><a href="#">Tarfis</a></li>');
const $social_header = $("#social-header");
const $menu = $("#menu");

$(window).resize(function() {
  if ($(this).width() > 800) {
    $tarif.prependTo($social_header);
    $menu.find('.tarif').remove();
  } else {
    $tarif.appendTo($menu);
    $social_header.find('.tarif').remove();
  }
});

話雖如此,我強烈建議您使用 CSS 而不是 JS 來解決您的目標。 您當前的方法很脆弱,因為有人在瀏覽器中簡單地禁用 JS 很容易破壞它,而且 UI 和 JS 代碼的分離也不是很好。

要在 CSS 中執行相同的操作,請在頁面加載時將所有 HTML 放在 DOM 中,並以這種方式組織您的 CSS:

#menu .tarif { display: none; }
#social-header .tarif  { display: block; }

@media screen and (min-width: 0px) and (max-width: 800px) {
  #menu .tarif { display: block; }
  #social-header .tarif  { display: none; }
}

您可以直接使用insertBefore/appendChild屬性

if ($(this).width() > 800) {
  social_header.insertBefore(tarif, social_header.firstChild)
}else{
  menu.appendChild(tarif);
}

由於一個節點不能有多個父節點,它將從當前父節點中刪除。

順便說一句,混合過多的香草 JS 和 jQuery 並不總是一個好主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM