jQuery - if text in DIV was clicked
Solution 1
Check the type of source if div then it means it would be text wrapped directly by the div. If you want to include mode tag like em
then you can add those in condition.
$('div').click(function(evt){
if(evt.target.tagName == 'DIV')
alert("div clicked");
});
Solution 2
You could use some jQuery magic and look at the children of the div
, however I would add a span
or label
inside your divs and give it a class/id:
<span class="letters">
Letters in new line
</span>
$(".letters").click(function() {
alert('Clicked');
});
The fiddle provided shows how to use it with children()
as well as the method mentioned above.
Demonstrating using a class rather than an ID.
Solution 3
You can stop the propagation of the event from all children of the divs:
$('div').click(function (event) {
alert('Text');
});
$('div').children().click(function (event) {
event.stopPropagation();
});
Solution 4
Would it not be viable to use a Span with the class text
With this code
$(".text").click(function() {
alert("Handler for click() called.");
});
( answer posted from phone, untested code. Post will be spellchecked once at a pc )
Solution 5
This is quite simple:
$('div').click(function (e) {
if ($(this).children().length === 0) {
// do something
alert($(this).text());
}
});
$('div').children().click(function (event) {
event.stopPropagation();
});
Patrik
Updated on June 14, 2022Comments
-
Patrik almost 2 years
I have some DIVs. Inside these DIVs are some texts, images, tags... I need to show "alert", when text is clicked. Not images, not other tags, not text in other tags... just text inside DIVs. How to do it with jQuery ?
HTML
<div style="background-color:PapayaWhip;">Some text. <img src="http://ynternet.sk/test2/close_1.jpg" /> <img src="http://ynternet.sk/test2/close_2.jpg" /> </div> <div style="background-color:Moccasin;">This are letters <em>and this are not.</em> Hello again! </div> <div style="background-color:LightGoldenRodYellow;"> <img src="http://ynternet.sk/test2/close_1.jpg" /> <img src="http://ynternet.sk/test2/close_2.jpg" /> Letters in new line. <img src="http://ynternet.sk/test2/close_1.jpg" /> <img src="http://ynternet.sk/test2/close_2.jpg" /> </div> <div style="background-color:Wheat;">New letters in another line.</div>
CSS
div { padding:10px 0px 0px 20px; font-family:Verdana; height:40px; } em{ color:red; }
-
Anthony Grist about 11 yearsBetter off using a class, since the
id
attribute of every element on the page should be unique. -
Darren about 11 years@AnthonyGrist true. Adjusted.
-
Anthony Grist about 11 yearsThis is really the best answer. It doesn't require any changes to the HTML and uses the minimum number of event handlers. It wouldn't handle nested
<div>
elements, but the question doesn't indicate that's a requirement or possibility, so no need to do so. -
Mark Jones about 11 yearsIn heine sight you could use would .. $('div').text().click(function {}). Work