Is it possible to select all the text an an element (e.g., a paragraph <p>) with JavaScript? A lot of people think jQuery .select() would do this, but it does not. It merely triggers an event. Note that DOM objects for <input> elements have a native select() method, but most other elements (such as <output> and <p>) do not.
(Do I need to use content-editable to get this to work?)
If you need to support later browsers, i.e., IE9+, you can use the following
document.querySelector('button').addEventListener('click', function(){
var range = document.createRange();
var selection = window.getSelection();
range.selectNodeContents(document.querySelector('p'));
selection.removeAllRanges();
selection.addRange(range);
});
Hello <p>Select me</p> World
<button id ='btn'>Select text</button>
Related links:
The spec: http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level2-Range-method-selectNodeContents
http://help.dottoro.com/ljcpcpnt.php
https://developer.mozilla.org/en-US/docs/Web/API/range.selectNodeContents
https://developer.mozilla.org/en-US/docs/Web/API/Selection.addRange
For support across all browsers, see https://github.com/timdown/rangy from https://stackoverflow.com/users/96100/tim-down
select() Will only work on <input> and <textarea> elements...
Also yes, you will have to use:
contenteditable="true"
And use .focus() to select all the text.
Try this:
<p id="editable" contenteditable="true"
onfocus="document.execCommand('selectAll',false,null);">Your Text Here</p>
<button onclick="document.getElementById('editable').focus();" >Click me</button>
JSFiddle Demo
Related
Is it possible to make a contenteditable paragraph focused with a button.
I've tried making the paragraph focused (like you would with an input), but it doesn't work. Like this:
document.getElementById("example").focus();
This is an example of what it should look like (I used input for this example):
https://jsfiddle.net/7rwft2c3/
The element you would like to focus must be editable first. According to the spec, you can only .focus() on a focusable area.
The spec says:
The term focusable area is used to refer to regions of the interface
that can become the target of keyboard input.
Here: https://html.spec.whatwg.org/multipage/interaction.html#focusable-area
So add the contentEditable attribute first, and then .focus() the element.
Per the comment below, .blur() is not necessary because once the contentediable attribute is removed, the element can no longer be focused.
Note here I changed the <input> to a <div>:
const el = document.getElementById("myText");
function getFocus() {
el.setAttribute('contenteditable', 'true');
el.focus();
}
function loseFocus() {
el.removeAttribute('contenteditable');
}
<div id="myText">A Div</div>
<button type="button" onclick="getFocus()">Get focus</button>
<button type="button" onclick="loseFocus()">Lose focus</button>
just brushing up on my javascript skills and trying to figure out why getElementsByClass isn't working for my code. The code is pretty simple. Upon clicking a button "clicky", the script will create a child h1 element of div. It works perfectly fine when I use getElementById and changing the div class to Id but doesn't work when I change it to class.
I've tried, getElementsByClassName, getElementsByClass, getElementsByTagName and changing the div to the appropriate attribute but no luck.
<!doctype html>
<html>
<body>
<p>Click on button to see how appendChild works</p>
<button onclick="myFunction()">Clicky </button>
<script>
function myFunction(){
var first = document.createElement("H1");
var text = document.createTextNode("Jason is pretty awesome");
first.appendChild(text);
document.getElementsByName("thistime").appendChild(first);
}
</script>
<div class="thistime">Hi</div>
</body>
</html>
You need to update your code from
document.getElementsByName("thistime").appendChild(first);
to
document.getElementsByClassName("thistime")[0].appendChild(first);
For reference - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
Working code - http://plnkr.co/edit/k8ZnPFKYKScn8iYiZQk0?p=preview
You could use getElementsByClassName(), which is supported in IE9+:
document.getElementsByClassName("thistime")[0].appendChild(first);
But a better alternative may be querySelector(), which is supported in IE8+
document.querySelector(".thistime").appendChild(first);
Note that querySelector() uses CSS selector syntax, so you should place a dot (.) before the class.
Snippet:
function myFunction() {
var first = document.createElement("H1");
var text = document.createTextNode("Jason is pretty awesome");
first.appendChild(text);
document.querySelector(".thistime").appendChild(first);
}
<p>Click on button to see how appendChild works</p>
<button onclick="myFunction()">Clicky</button>
<div class="thistime">Hi</div>
As you have noticed, the function is called getElementsByName with "elements" being a plural.
It returns a list of markups by their name (and not their css class).
You need to use the function that handles the class name, and get the first element of the array, or loop on all the results, depending on what you are looking for.
I find myself in a situation where I want to get the target element that triggered the selectionChange dom event.
But judging by https://developer.mozilla.org/en-US/docs/Web/Events/selectionchange, it seems that the element in e.target is always the document object in the normal (non-input, non-textarea) case.
So does that mean I will have to manually call window.getSelection, and figure out the current cursor location and find the dom node that way?
Does anyone know of a short cut? or some working example would be nice.
If your element can become an active element, use document.activeElement to get the element we're selecting inside of. This will work with textareas, inputs, and on elements whose tabindex is set.
// NOTE: activeElement can only be found on selectable elements!
document.addEventListener('selectionchange',function(){
document.getElementById('currentTag').innerHTML = document.activeElement.tagName;
});
#currentTag{
font-weight:bold;
}
<textarea>This is sample text you can replace and move your cursor within. Whee!</textarea>
<br><input type="text" placeholder="Input">
<p tabindex="0">P tag text is the best tag text. <span color="blue">Unless you have a span.</span></p>
<ol tabindex="0">
<li tabindex="0">Item 1</li>
<li tabindex="0">Item 2</li>
</ol>
<p id="currentTag"></p>
You can use document.selection to get what is currently selected.
Example taken from http://help.dottoro.com/ljixpxji.php
<head>
<script type="text/javascript">
document.onselectionchange = OnChange;
function OnChange () {
var range = document.selection.createRange ();
if (range.text.length == 0) {
alert ("The current selection is empty");
}
else {
alert ("The contents of the current selection are\n" + range.text);
}
}
</script>
</head>
<body>
Select this text on this page!
</body>
--EDIT--
As pointed out by #user1017674 this code does not work in chrome, after a little bit of research I found document.selection should only be used in IE < 9. It seems that window.getSelection() is still going to be the best way to get it.
Ref. Does chrome supports document.selection?
I have this HTML:
<div class="test">Orange <span class="is">is</span> my favorite color.</div>
I only want to replace Orange (and the space after it). Using .text() won't work because it selects the whole strong.
How do I do this?
This is harder to do with jQuery than with the native DOM, so if you're using jQuery, you're going to have to convert the element to the native DOM using jQuery's array indexing.
Basically, what we need to do is change the first text node. jQuery isn't really good with text nodes, which is why we use the DOM here:
//This gets the div.test element using jQuery:
var testDiv = $("div.test");
function changeColor(color) {
/* The following function changes the value of the first text node within testDiv: */
//This converts testDiv from a jQuery element to a regular DOM element. This is because jQuery isn't really meant to be handling stuff like text nodes, so doing this with the regular DOM will just be much easier.
var domElement = testDiv[0];
//Now, just change the value of the first text node:
domElement.childNodes[0].nodeValue = color;
}
//Now, as you can see if you click div.test, we can replace the color mentioned in div.test using changeColor():
testDiv.click(function() {
changeColor("Blue ");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Orange <span class="is">is</span> my favorite color.</div>
You should use native DOM methods. In your case the simples thing is just change nodeValue property of the first childNode element (which you know is going to be TextNode element):
var el = $('.test');
el[0].childNodes[0].nodeValue = 'Green ';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Orange <span class="is">is</span> my favorite color.</div>
or if you want you can grab text node with jQuery's $.fn.contents method:
var el = $('.test');
el.contents()[0].nodeValue = 'Green ';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Orange <span class="is">is</span> my favorite color.</div>
If you are using jquery, here is the solution
$('.test').html(function(){
return $(this).html().replace('Orange ','');
});
Find the fiddle here: https://jsfiddle.net/MasoomS/xff6dw1t/
Used data attribute to refine the code and to use it for multiple strings
HTML:
<div class="test" data-replace="Orange ">Orange <span class="is">is</span> my favorite color.</div>
<div class="test" data-replace="Green ">Green <span class="is">is</span> my next favorite color.</div>
JQUERY:
$('.test').html(function(){
return $(this).html().replace($(this).data('replace'),'');
});
document.getElementsByClassName("test")[0].childNodes[0].nodeValue = "Black";
using Javascript, it is easy to programatically select the text inside a textarea or input text element. How about for
<span>The quick brown fox jumps over the lazy dog</span>
is it possible to use JavaScript to select the words "quick brown fox"? Or select the whole sentence?
Courtesy of http://www.sitepoint.com/forums/showthread.php?t=459934
<script type="text/javascript">
function fnSelect(objId) {
fnDeSelect();
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(objId));
range.select();
}
else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(objId));
window.getSelection().addRange(range);
}
}
function fnDeSelect() {
if (document.selection) document.selection.empty();
else if (window.getSelection)
window.getSelection().removeAllRanges();
}
</script>
<body>
<div id="test1">
<p>jhsdgfhlsdlfkjsdklgjs</p>
<p>jhsdgfhlsdlfkjsdklgjs</p>
<p>jhsdgfhlsdlfkjsdklgjs</p>
</div>
<div id="test2">
<p>jhsdgfhlsdlfkjsdklgjs</p>
<p>jhsdgfhlsdlfkjsdklgjs</p>
<p>jhsdgfhlsdlfkjsdklgjs</p>
</div>
Select 1
Select 2
DeSelect
</body>
You will need some way to manipulate the span tag. Such as an id, but then in javascript I would edit some of the style properties. You could have a property for everything you want to highlight like what is shown below.
.HL {
background: #ffff99;
color: #000000;
}
If you do that then you will need to get a reference to the specific tag.
DocumentgetElementsByTagName("title")
Otherwise Document.getElementByID("ID") is good for unique ids.
Then using setAttribute(name, value) To change the class to the one given.
This is just a simple example but there are many ways to do this.
<span id="abc" class=""> Sample </span>
var temp = Document.getelementByID("abc");
temp.setAttribute('class', 'HL');
in css you could create a .highlight class
.highlight{
background-color:yellow;
}
in javascript you could add the .highlight class to the elements you wish to highlight
<getSpanElement>.className='highlight';
this text is then highlighted, though it is not selected.
Highlight or select? I think you actually want to select not to highlight.
Highlight... yes! Set the proper CSS properties of the span element, for instance foreground and background color.
Edit: That is called selecting. Sorry, I don't know of any way to do it.