如何在CSS中选择彼此相邻的特定元素

时间:2019-04-19 21:34:19

标签: html css

我的HTML结构是这样的:

input span input

现在,我想通过搜索具有类似结构的元素来选择第一个和第二个输入。我已经尝试过使用+运算符,但是那样,我只能像这样选择第二个输入:

input + span + input

我也需要同时选择第一个输入。

2 个答案:

答案 0 :(得分:0)

我猜你的实际结构看起来像这样

<input />
<span></span>
<input />

,并且您希望能够访问输入元素?而且这种结构可以在整个html中重复吗?

如果是这种情况,您将需要使用ajax / jquery之类的方法来执行此操作。在javascript中,您可以执行以下操作...

<input id="input1" class="" />
<span></span>
<input id="input2" class="" />

JavaScript

document.getElementById('input1').className = "class1";
document.getElementById('input2').className = "class2";

答案 1 :(得分:0)

我不知道我是否理解正确,但是你的代码是否是这样的:

<input type="email" name="email" placeholder="Email />
<span> Take your time and enter your age </span>
<input type="number" name="age" placeholder="Age />

您的CSS选择器仅应输入,因为这段代码:

input {
    background-color: #fabada;
    width: 200px;
}
<input type="email" name="email" placeholder="Email" />
<span> Take your time and enter your age </span>
<input type="number" name="age" placeholder="Age />

这应该覆盖这两个元素(以及文档中包含的任何其他输入元素)。如果您想了解更多,这是一个很棒的在线游戏,可以了解CSS选择器https://flukeout.github.io/享受