Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select input tag when followed by span tag?

Tags:

html

jquery

css

I want to select an input tag when it is followed by span :

HTML :

<input type="text"/>
<span>
    ...
</span>

CSS :

input [followed span] {
    padding:5px; (set input padding, only when followed by span)
}
like image 926
simple guy Avatar asked Feb 26 '18 03:02

simple guy


2 Answers

You can use + selector to Selects all <span> elements that are placed immediately after <input> elements

input + span {
    background-color: yellow;
}
<input type="text">
<span>test</span>

If you want to select <input> that is placed before <span>. this is not doable in css since,

Cascading Style Sheets : A cascade is like a waterfall, there’s no backward motion. So, naturally, there is no previous sibling selector in CSS.

Read more https://www.wikitechy.com/technology/previous-sibling-css-selector/


what you can try is .prev() of jQuery..

$(document).ready(function(){
    $('span').prev().css('background','yellow');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text">
<span>test</span>

For more info about .prev() https://www.w3schools.com/jquery/traversing_prev.asp

like image 132
davecar21 Avatar answered Oct 02 '22 20:10

davecar21


This will return content in span tag but uh need to specify at which input tag you're pointing either by using class or id for exact result.

$("input").closest("span").html()
like image 44
Ronak Bokaria Avatar answered Oct 02 '22 20:10

Ronak Bokaria