I want to focus each "p" tag separately when I click on it, like a CSS "focus:" on an input. The problem is that the selector "focus" doesn't work on paragraphs, here is an exemple :
HTML
<div id="myDiv">
<p>Some Content 1</p>
<p>Some Content 2</p>
<p>Some Content 3</p>
<p>Some Content 4</p>
</div>
CSS
#myDiv p:focus {background-color:red;}
How can I find an alternative solution to make it work?
I want to focus each "p" tag separately when I click on it, like a CSS "focus:" on an input. The problem is that the selector "focus" doesn't work on paragraphs, here is an exemple :
HTML
<div id="myDiv">
<p>Some Content 1</p>
<p>Some Content 2</p>
<p>Some Content 3</p>
<p>Some Content 4</p>
</div>
CSS
#myDiv p:focus {background-color:red;}
How can I find an alternative solution to make it work?
Share Improve this question edited Sep 4, 2015 at 15:02 Akshay 14.3k5 gold badges47 silver badges71 bronze badges asked Sep 4, 2015 at 14:19 Horai NuriHorai Nuri 5,57817 gold badges84 silver badges136 bronze badges2 Answers
Reset to default 18You can add tabindex
to the p
tag to achieve this
#myDiv p:focus {
background-color:red;
}
<div id="myDiv">
<p tabindex="0">Some Content 1</p>
<p tabindex="0">Some Content 2</p>
<p tabindex="0">Some Content 3</p>
<p tabindex="0">Some Content 4</p>
</div>
Jquery solution will be
click = false;
$(document).click(function(e) {
if(!($(e.target).is('p'))) {
$('p').css('background', 'transparent')
}
})
$('p').click(function() {
$('p').css('background', 'transparent');
$(this).css('background', 'red');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="myDiv">
<p>Some Content 1</p>
<p>Some Content 2</p>
<p>Some Content 3</p>
<p>Some Content 4</p>
</div>
Here is a javascript only version:
function highlight(theP)
{
var x = document.getElementsByTagName("p");
var i;
for (i = 0; i < x.length; i++)
{
x[i].style.background = "";
}
theP.style.backgroundColor = "red";
}
<div id="myDiv">
<p onclick="highlight(this);">Some Content 1</p>
<p onclick="highlight(this);">Some Content 2</p>
<p onclick="highlight(this);">Some Content 3</p>
<p onclick="highlight(this);">Some Content 4</p>
</div>