Reputation: 12512
I have a div element with some text in it. I need to be able to select: 1. div itself, and 2. only text within that div
<div class="myDiv">some text</div>
So I am able to select div, by class name
$(".myDiv").hover(...);
But I'm having difficulty with the text. Tried the following
$(".myDiv").contents().eq(0).text().hover(...);
but no luck. Also, when I hover over text I need to select that text only, and not the parent div.
Upvotes: 0
Views: 999
Reputation: 4624
Try this
I guess this is what you need
(function findTextNodes(current, callback) {
for(var i = current.childNodes.length; i--;){
var child = current.childNodes[i];
if(3 === child.nodeType)
callback(child);
findTextNodes(child, callback);
}
})(document.getElementById('myDiv'), function(textNode){
$(textNode).replaceWith('<span class="textNode">' + textNode.nodeValue + '</span>');
});
$('.textNode').hover(function(){
$(this).css('color', 'white');
},function(){
$(this).css('color', 'black');
});
Upvotes: 1
Reputation: 84
If your trying to add text try:
$(".myDiv").contents().eq(0).innerHTML('YOUR TEXT HERE').hover(...);
Upvotes: 0
Reputation: 56501
var html= $('.myDiv').html(); // Select div itself
var text= $('.myDiv').text(); // To get only the text
Upvotes: 0
Reputation: 4798
All you should need is the following:
var txt = $('.myDiv').text();
Upvotes: 3