Reputation: 4648
I'm having the following html code and trying to select text which is located immediate to img tag while clicking the respective img tag.
For example in the first <p>
tag I should get "Politics",
<p>Environmental<img src="/img/bookmark.png" class="bookmark" id="bm1" data-username="usernames" data-userid="un123"> Politics</p>
<p>Science<img src="/img/bookmark.png" class="bookmark" id="bm2" data-username="usernames" data-userid="un123"> Explore</p>
<p>Contextual<img src="/img/bookmark.png" class="bookmark" id="bm3" data-username="usernames" data-userid="un123"> Learning</p>
I've used the following jQuery function, but nothing helped.
$("img.bookmark").click(function(){
console.log($(this).next());
});
Upvotes: 0
Views: 113
Reputation: 902
*nextSibling.data* will give you the text (in your case Politics/../..)
$("img.bookmark").click(function(){
alert(this.nextSibling.data);
});
Upvotes: 1
Reputation: 74738
You stated this For example in the first <p> tag I should get "Politics",
You can get it with .nextSibling.nodeValue
:
$("img.bookmark").click(function(){
console.log(this.nextSibling.nodeValue);
});
Upvotes: 2
Reputation: 237965
The next
jQuery function gets the next element. You want a text node. You need to use normal DOM traversal methods to get this: you need the nextSibling
property.
$("img.bookmark").click(function(){
console.log(this.nextSibling);
});
You probably actually want its string value, for which you can use nodeValue
:
$("img.bookmark").click(function(){
console.log(this.nextSibling.nodeValue);
});
Upvotes: 5