How can I get the DOM element which contains the current selection?
In IE, use document.selection.createRange().parentElement() and in real browsers use window.getSelection().getRangeAt(0).startContainer.parentNode. Something like this:
function getSelectedNode()
{
if (document.selection)
return document.selection.createRange().parentElement();
else
{
var selection = window.getSelection();
if (selection.rangeCount > 0)
return selection.getRangeAt(0).startContainer.parentNode;
}
}
Determine which DOM elements the current text selection contains
window.getSelection()
gives you a Selection object. Use selection.rangeCount
and selection.getRangeAt()
to get a Range object representing which selection you want.
Now you can get the first and last nodes in the selection from range.startContainer
/startOffset
and range.endContainer
/endOffset
. You could then walk up and down the tree to pick up all the elements in between those two positions, eg. using the getElementsBetweenTree()
function from this answer.
Unfortunately, IE's TextRange model is totally different to the W3 and HTML5 standard, and in general much worse. It does't give up the start and end positions nearly as easily, and not in any reliable way. All you get is parentElement
to tell you the common ancestor, and from there you're limited to guessing where the range is based on creating a new Range and calling moveToElementText
on it then compareEndPoints
with the selection range. And if you need to know the exact text selection you're then guessing based on moveStart
/moveEnd
ing the range and comparing, which isn't fun at all.
how to get selected DOM using javascript if selected text is HTML?
You can try this approach.. (if only you've direct text node in your div)
window.getSelection().focusNode.parentElement //returns the selected element
so you can set attr like
window.getSelection().focusNode.parentElement.setAttribute('data-id', 'id-1');
You can wrap it in a 'mouseup' event with your current div
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="myDiv">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id natus voluptatibus eum explicabo soluta excepturi?
</div>
<div id="myDiv2">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id natus voluptatibus eum explicabo soluta excepturi?
</div>
<script>
var myDiv = document.getElementById('myDiv')
myDiv.addEventListener('mouseup', function(){
window.getSelection().focusNode.parentElement.setAttribute('data-id', 'id-1');
})
</script>
</body>
</html>
Or it is best approach to add attr to selected 'div' only, if there is many divs
var div = document.querySelectorAll('div')
for(var i = 0; i < div.length; i++){
div[i].addEventListener('mouseup', function(){
window.getSelection().focusNode.parentElement.setAttribute('data-id', 'id-1');
}, false)
}
DOM find current selected drop down element
Option 1
HTML
<select id="Quantity" name="Quantity"
class="quantity_select" onchange="SetValue(this.value)>
<option id="1" selected="selected" value="1">1</option>
<option id="2" value="2">2</option>
<option id="3" value="3">3</option>
</select>
JavaScript
function SetValue(val) {
alert(val); // This will be the selected value in the drop down
}
Option 2
If you already have JS in place, and don't want to use option 1, you can simply get the value with getElementById()
:
var ddl = document.getElementById('Quantity');
var val = ddl.options[ddl.selectedIndex].value;
How can I get the element in which highlighted text is in?
Try something similar to this to get the dom element that contains the selected text.
window.getSelection().anchorNode.parentNode
It works on firefox and Chrome, you should test it into the remaining browsers.
It have a quirk, if you select text that beholds to more than an element, only the first one is returned. But maybe you can live with this.
Just for reference on what is the anchorNode property:
http://help.dottoro.com/ljkstboe.php
On internet explorer this snippet should do the trick (I can't test it)
document.selection.createRange().parentElement();
as stated into
http://msdn.microsoft.com/en-us/library/ms535872.aspx and
http://msdn.microsoft.com/en-us/library/ms536654.aspx
A range explanation on quirksmode: http://www.quirksmode.org/dom/range_intro.html
How to know if there is a link element within the selection
I ended up going with a solution like this:
var findinselection = function(tagname, container) {
var
i, len, el,
rng = getrange(),
comprng,
selparent;
if (rng) {
selparent = rng.commonAncestorContainer || rng.parentElement();
// Look for an element *around* the selected range
for (el = selparent; el !== container; el = el.parentNode) {
if (el.tagName && el.tagName.toLowerCase() === tagname) {
return el;
}
}
// Look for an element *within* the selected range
if (!rng.collapsed && (rng.text === undefined || rng.text) &&
selparent.getElementsByTagName) {
el = selparent.getElementsByTagName(tagname);
comprng = document.createRange ?
document.createRange() : document.body.createTextRange();
for (i = 0, len = el.length; i < len; i++) {
// determine if element el[i] is within the range
if (document.createRange) { // w3c
comprng.selectNodeContents(el[i]);
if (rng.compareBoundaryPoints(Range.END_TO_START, comprng) < 0 &&
rng.compareBoundaryPoints(Range.START_TO_END, comprng) > 0) {
return el[i];
}
}
else { // microsoft
comprng.moveToElementText(el[i]);
if (rng.compareEndPoints("StartToEnd", comprng) < 0 &&
rng.compareEndPoints("EndToStart", comprng) > 0) {
return el[i];
}
}
}
}
}
};
Where getrange() is another function of mine to get the current selection as a range object.
To use, call it like
var link = findselection('a', editor);
Where editor is the contenteditable element, or body in a designmode iframe.
Replicate HTML source of a DOM element in current state
You could just wrap your select
in another element. Then you'd be able to select it by id, get the parent node, then the parent node's innerHTML
. If you want to show which option
is currently selected, you can place the selected
attribute on it.
document.getElementById('selectId').addEventListener('change', function() { var opts = this.getElementsByTagName('option'); for (var i = 0; i < opts.length; i++) opts[i].removeAttribute('selected'); this.querySelector('option:checked').setAttribute('selected', 'selected'); console.log(this.parentNode.innerHTML);});
<div class="select-wrapper"> <select id="selectId"> <option>Yes</option> <option>No</option> </select></div>
Related Topics
How to Check Whether a Storage Item Is Set
JavaScript Confirm Popup Yes, No Button Instead of Ok and Cancel
Get Next/Previous Element Using JavaScript
Case Insensitive Xpath Contains() Possible
How to Use HTML Tags in the Options For Select Elements
How to Calculate the Number of Days Between Two Dates
How to Clear the Contents of an Iframe from Another Iframe
Selecting All Text in HTML Text Input When Clicked
How to Set Value of Input Text Using Jquery
How Exactly Does ≪Script Defer="Defer"≫ Work
Performance of Mutationobserver to Detect Nodes in Entire Dom
How to Calculate the Xpath Position of an Element Using JavaScript
Including Both Href and Onclick to HTML ≪A≫ Tag
Stop/Close Webcam Stream Which Is Opened by Navigator.Mediadevices.Getusermedia