【问题标题】:target and remove containing parent div tag not the contents定位并删除包含父 div 标签而不是内容
【发布时间】:2017-11-16 14:16:11
【问题描述】:

我有一段我无法完全控制的代码,其中包括一个没有类或 ID 的 Div。我想删除此 Div 的开始和结束标记并保留现有内容,但不确定如何定位并删除?

目前...

<li id="foo" class="underline">

<div>
<input id="username" name="username" required="required" class="validate" type="text">
</div>

<label for="username">Username</label>

</li>

我想要的最终结果...

<li id="foo" class="underline">

<div class="mynewdiv">

<input id="bar" name="bar" required="required" class="validate" type="text">
<label for="bar">Username</label>

</div>

</li>

我可以控制添加 newDiv。我的问题与how can I remove wrapper (parent) without removing the child 有相似之处 但我不确定如何正确定位这个未命名的 div(最接近?)。谢谢

【问题讨论】:

  • 我投票决定将此问题作为离题结束,因为 SO 是来帮助您编写代码的,但 SO 不是来为您编写代码的。
  • 为什么你不能给&lt;div&gt;一个id或者从html中删除&lt;div&gt;?这是否必须在运行时进行更改?
  • 我无法完全控制框架中的代码来更改
    。非常感谢 Carsten 的回答。抱歉,我不认为我的代码尝试值得添加。

标签: javascript jquery html


【解决方案1】:

您可以在 div 上使用 .append() 并在其中找到 label

$(".underline div").append(function(){
  return $(this).next("label");
}).addClass("mynewdiv");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="foo" class="underline">

  <div>
    <input id="username" name="username" required="required" class="validate" type="text">
  </div>

  <label for="username">Username</label>

</li>

【讨论】:

  • 而不是 #foo 使用 .underline 。可能是他有更多具有相同 id(意外)和类的元素。在这种情况下,Class 将起作用,但 id 将不起作用。还要添加关于此的注释
  • @AlivetoDie 真的,我已经听取了你的建议并更改了代码,谢谢
  • 非常感谢,我在列表元素上使用了一个通用类。
猜你喜欢
  • 2012-04-08
  • 1970-01-01
  • 1970-01-01
  • 2019-03-22
  • 2012-09-29
  • 2021-10-09
  • 1970-01-01
  • 2020-07-23
  • 2019-04-09
相关资源
最近更新 更多