Vanilla JS: select an element but no child elements

Hello, all,

I’m not on a project, just trying to get a better feel for vanilla JS (even though I’ve been working with it since early 2001.) And I have a question.

How do I select an element, but not any child elements. For example:

I have a form that contains an input type=“text” and a select with several options. Just goofing around, I decided that I wanted to see how to track cursor movement around the form. Easily enough done (as you will see in a moment.) But it resets the coordinates when the cursor passes over the input and the select and gives the coordinates within those child elements. I’d like to not get those, preferring to keep getting the coordinates within the parent form. Is there a way to exclude child elements?

Here’s my code:

	<form style="border: 1px solid black; display: inline-block; width: 1000px; height: 500px;">
		Enter a value, then choose what conversion type: <input type="text" id="thisValue" name="thisValue" />
		<select id="conversionType" name="conversionType">
		<option value="">Select</option>
		<option value="f2c">F to C</option>
		<option value="c2f">C to F</option>
		<option value="m2k">MPH to KPH</option>
		<option value="k2m">KPH to MPH</option>
		<option value="i2c">in to cm</option>
		<option value="c2i">cm to in</option>
		<option value="y2m">yd to m</option>
		<option value="m2y">m to yd</option>
		</select>
	</form>
	<div id="coord"></div>

<script>
var thisForm = document.forms[0], coord = document.getElementById('coord');
thisForm.addEventListener('mousemove',giveXY,false);
		function giveXY(e){
		  var rect = e.target.getBoundingClientRect();
		  var x = (e.clientX - rect.left).toFixed(0);
		  var y = (e.clientY - rect.top).toFixed(0);
		  coord.innerHTML = x + ', ' + y;
			}
</script>

If you copy/paste into a htm page and open in FF, you’ll see what I mean.

Any suggestions? Thank you.

V/r,

^ _ ^

You could check if the parentNode of the element is the form, and only proceed if it is.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.