View Full Version : Retrieving tag Names of selection (dhtml)
Ben Chivers
07-15-2002, 06:32 PM
This is a dhtml question, I would post this in a dhtml forum if there was one.
How can I retrieve the tag names of a current selectionin a document?
I've used the following code but had no luck with retrieving the tag names.
<html>
<head>
<script>
function displaytag(){
var selection = document.selection.createRange();
alert(selection.tagName);
}
</script>
<title>New Page 1</title>
</head>
<body>
<p>Some sample text!</p>
<p><input type="button" onclick="displaytag()" value="Display Tag" name="B3"></p>
</body>
</html>
Please help me, any help would be most appreciated!
Many Regards,
Ben Chivers
This should work in Gecko-based browsers (NS6, NS7, Mozilla, K-meleon, Galeon, Beonex, etc):
var tagname = window.getSelection().getRangeAt(0).commonAncestorContainer.nodeName;
If all the selection is within one tag, tagname will be #text, as the text node contains all of the selection. You'd need to call the text node's parentNode if you wanted to get the containing tag.
If it spans multiple tags, you will get "TAGNAME" for the value.
I don't know the equivalent code for IE, but am pretty sure you can do something with the TextRange object...
Ben Chivers
07-15-2002, 09:18 PM
Thanks for your reply, but I need to know how to do it in Internet Explorer. I know you need to use the text range object, but need help displaying the tagnames of the current selection.
Thanks
Ben Chivers
07-16-2002, 01:01 PM
I really need help displaying tag names of the current selection.
Anybody who helps me achieve my objective will receive a free web based perl program to run of their server at the end of it worth at least $50.
Please help me!
mordred
07-16-2002, 04:23 PM
<head>
<script>
function displaytag() {
var selection = document.selection.createRange();
if (selection.htmlText.length > 0) {
return selection.htmlText.match(/<[a-z0-9]+?>/ig);
} else {
return false;
}
}
</script>
<title>New Page 1</title>
</head>
<body>
<h3>A test</h3>
<br />
<p>Some <b>sample</b> text!
</p>
<p><input type="button" onclick="alert(displaytag())" value="Display Tag" name="B3"></p>
</body>
</html>
Works for me with IE5.5 on Win2k.
So what have I won - a free perl program? :)
Ben Chivers
07-16-2002, 04:37 PM
Cheerz!
You have won a cruise to the caribbean......u wish!
A WYSIWYG editor for editing and creating webpages on your web server. The program isn't currently finished yet, but it will be finished next week and will be very good, including dhtml effects. Please contact me next week, when I will have it finished.
Thanks again!
Ben Chivers
07-16-2002, 04:38 PM
sorry, here's the email address:
webmaster@easyscripts.co.uk
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.