繁体   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