如何在特定字段后添加类?

时间:2018-08-30 05:49:32

标签: javascript jquery

我在html下方。

<input class="form-control dropify" name="photo" type="file">

<button type="button" class="dropify-clear">Remove</button>

现在我必须使用上面的输入名称deletephotodropify-clear上添加name="photo"类名称。像这样:

<button type="button" class="dropify-clear deletephoto">Remove</button>

2 个答案:

答案 0 :(得分:3)

使用jquery,您可以使用next

下面的代码将选择一个类为dropify-clear的按钮,该按钮位于带有名称photo的输入旁边,并将使用jquery addClass添加一个类

$("input[name='photo']").next("button.dropify-clear").addClass('deletephoto')
.deletephoto {
  background: red;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="form-control dropify" name="photo" type="file">
<button type="button" class="dropify-clear">Remove</button>

答案 1 :(得分:1)

没有jquery,您可以这样做:

const removeBtn = document.querySelector(".dropify-clear");
removeBtn.classList.add("deletephoto");
.deletephoto {
  background: red;
  color: white;
}
<input class="form-control dropify" name="photo" type="file">

<button type="button" class="dropify-clear">Remove</button>