I’m using jquery mouseenter/leave to try to change the (currently-hovered-over) TEXT inside a container without changing any other child elements.
I’m using this on top of a live 3rd party website – this means I have no control over the HTML code, which gives me the following issues:
- I don’t know how many child elements are in the parent container
- the HTML tags (both parent and children) could be anything from LI, to IMG, to A, to SPAN, to H1, etc
- the position of the text I need to change will vary from 1st to last
and anything in-between
I’ve tried the following (nameX and indexX are used to identify the current element – I can’t use ‘this’ on it’s own as I need to use the actual values elsewhere):
$("a,img,p").mouseenter(function (event) {
nameX = this.tagName;
indexX = $(nameX).index(this);
$(''+nameX+':eq('+indexX+')').text("hello");
});
<ul>
<li>
<a href="">bullet 1
<img src="http://bit.ly/ZqJ1DL" width="229" height="129"/>
</a><br>
<a href="">bullet 2
</a><br>
<a href="">bullet 3
</a><br>
general text
</li>
</ul>
When I use the above – it DOES work when hovering over bullet 2 or bullet 3.
However, it does NOT work with bullet 1 – here the JS replaces ALL contents of the parent, including the image – I only want it to replace the TEXT and leave the image (and any other children) alone, regardless of the position of the the text.
See example FIDDLE HERE
[EDIT: the above HTML is example code – it could be anything as it will be the code of the 3rd party website I’m hovering over – please therefore comment on the JQuery code only – thanks, Steve]
this script selects all DOM elements within the anchor so it can replace them when changing the text:
http://jsfiddle.net/vvtgQ/
and here is a version that uses jQuery.contents() to work only on :text elements:
http://jsfiddle.net/eYSXp/