I want to allow a user to select, create a range, and then have javascript remove the underline on the range that the user selects. For example, If I have the code
<u> Hello, my name is Justin, and I have a question </u>
And the user selects "Justin, and I" and hits un-underline, would it be possible to change the HTML to:
<u> Hello, my name is </u>
Justin, and I
<u> have a question </u>
or if the entire sentence is selected, have the entire element deleted and replaced with normal text?
The solution has bugs if selected both underline and normal text at same time, i am trying to fix it.
getSelection() to get selected text.
getRangeAt(0) get selected index in string, remember to +3 because the length of <u> is 3.
Use slice() create new html and replace the old html.
function selected() {
let target = document.getSelection(),
range, res
if (target.toString() === '') return
range = target.getRangeAt(0)
if (range.commonAncestorContainer.parentElement.tagName != 'U') return
res = range.commonAncestorContainer.parentElement.outerHTML
let head = res.slice(0, range.startOffset + 3),
middle = `</u>${target.toString()}<u>`,
tail = res.slice(range.endOffset + 3)
range.commonAncestorContainer.parentElement.outerHTML = head + middle + tail
}
document.onmouseup = selected;
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<u>Hello, my name is Justin, and I have a question</u>
</body>
</html>
Related
Not being too versed with JS yet, I've run into a weird issue where it seems like .replace() should be working but isn't.
I'm just trying to take a string (from an element ID) that has text + digits, replace the digits with a RegEx pattern, then replace the original text in that ID with the original text + new digits.
My HTML sample:
<html>
<body>
<p>Click the button to replace "Movies: 12344" with "Movies: 54321" in the paragraph below:</p>
<p id="demo">Movies: 1234!</p>
<button onclick="myFunction()">Try it</button>
</body>
</html>
My JS:
function myFunction() {
// Get all the text in #id=demo
var str = document.getElementById("demo");
// RegEx pattern to find ": <some digits>"
var pat = /\:\s?\d*/;
// Replace the digits
var res = str.replace(pat, ': 54321');
// Doesn't work (as a test) ...
//res = " hi"
// Replace the text in id=demo with original text + new digits.
str.innerHTML = res;
// Doesn't work (as a test) ...
//document.getElementById("demo").innerHTML = res;
}
At the moment, after clicking the button in the page, nothing happens.
This might help out a bit too:
https://codepen.io/stardogg/pen/aboREmL
In the same way you're setting the innerHTML in the last line of your function, innerHTML is also what you should be applying the replace on:
function myFunction() {
var str = document.getElementById("demo");
var pat = /\:\s?\d*/;
var res = str.innerHTML.replace(pat, ': 54321');
str.innerHTML = res;
}
<p>Click the button to replace "Movies: 12344" with "Movies: 54321" in the paragraph below:</p>
<p id="demo">Movies: 1234!</p>
<button onclick="myFunction()">Try it</button>
Your str variable is not equal to the text node within the element, but rather the element itself. To make str equal to the text within the element, try the following.
var str = document.getElementById("demo").innerText;
You need to extract text from the element before replacing.
//Replace the digits
var res = str.innerHTML.replace(pat, ': 54321');
I'm trying to alert the last character of a string split, using innerHTML, but it's showing nothing in alert box.
this is my code
Html
<html>
<head>
<title>JavaScript basic animation</title>
<script type="text/javascript">
</script>
<script type="text/javascript" src="myfunction_2.js"></script>
</head> <body>
<div id="target">w3resource </div>
<button onclick="shubham()">click</button>
</body>
</html>
Function
function shubham()
{
var x=document.getElementById('target').innerHTML;
var y=x.split('');
var z=y[0];
var m=y[9];
var n=y[1]
var last=y[y.length-1]
alert(last);
}
it works properly if I take var x as
var x='w3resource';
but i need to take x value as
var x=document.getElementById('target').innerHTML;
so what should i do for this???
You need to use textContent instead of innerHTML. innerHTML gets you the actual HTML markup, including the tag angled brackets (<>), whereas textContent will give you just the text.
var x=document.getElementById('target').textContent.trim();
Your code code exactly what it should do - it alerts a last character of #target element (which is a whitespace in your case).
If you changed <div id="target">w3resource </div> to <div id="target">w3resource</div> (removed the space at the end) the result would be 'e'.
If you want to find the very last text character you would have to use:
function shubham() {
// Element reference
const element = document.getElementById('target');
// Text without spaces at the beggining and the end
const text = element.innerText.trim();
// Get the last character
const lastCharacter = text[text.length - 1];
// Alert the last character
alert(lastCharacter);
}
<div id="target">w3resource </div>
<button onclick="shubham()">click</button>
I see that you have a space in the target div:
<div id="target">w3resource </div>
Hence the last character is a blank space, remove all the blank space and it should work, use the function below :
function shubham3()
{
var x=document.getElementById('target').innerHTML.replace(/ /g,'');
var y=x.split('');
var z=y[0];
var m=y[9];
var n=y[1]
var last=y[y.length-1]
alert(last);
}
I'm trying to bold the first four characters of every item of an array (in this case a list), but all I know how to do is select whole strings:
$("li").slice(0).css("font-weight", "Bold");
How can I specify which of each string's characters I want to slice?
$('li').each(function() {
var $li = $(this);
var txt = $li.text();
$li.text(txt.substring(4));
$li.prepend($('<b/>').text(txt.substring(0,4)));
});
That iterates through each <li> tag and replaces the inner text with a bold tag containing the first four characters, and the remaining original text afterwards.
You could switch the <b> to a <span> to have more control over the style. You could also experiment with .html() if you need to preserve other markup within each list item.
Here is an example which may help you:
$("li").each(function() {
var len = $(this).text().length,
text1 = $(this).text().slice(0, 4),
text2 = $(this).text().slice(5, len);
$(this).html('<b style="color:red">' + text1 + '</b>' + text2);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>how-to-slice</li>
<li>specific</li>
<li>characters</li>
<li>in-every</li>
<li>item-of-an-array</li>
</ul>
I have this assignment for school and it really looks simple because the instructions are given, but I am having trouble solving it. Nothing gets displayed on my web page after pressing the search button.
Here it is:
Write a JavaScript script called "CharacterOccurences.JS” that inputs several lines of text and a search character and uses String method indexOf() to determine the number of occurrences of the character in text.
A) You have to use the external CSS file called "CharacterOccurences.CSS" to set the margin of the paragraph to the value 0 (zero).
B) You have to declare in your HTML form four (04) ids:
a. "searchString" as textarea id in paragraph with 4 rows and 55 columns
b. "characters" as input id in paragraph with text type and size equal 5
c. "searchButton" as input id in paragraph with button type and its value
equal "Search"
d. "output" as id in paragraph is for the final result.
C) The JavaScript file (CharacterOccurences.js) contains three (03) global variables and two (02) functions:
a. Global variables :
i. searchStr to get the id of "searchString"
ii. ch to get the id of "characters"
iii. outResult to get the id of "output"
b. The function getAllDomElement() that
i. Accesses the "searchButton" element and adds the search button using its id by using the existing the function addEventListener(), which takes three (03) arguments: (a) the name of event as a string literal (here is "click"), (b) the function searchOccurrences, and (c) the Boolean value false.
ii. Gets all id elements of "searchString", "characters", "output" using the existing function getElementById()
c. The function searchOccurrences() to search the character we look for and count the number of occurrences of that character.
i. 4 local variables: count, chValue, searchStr, result.
ii. Use the functions: charAt( 0 ), toLowerCase() and indexOf().
iii. If the variable count equal 0 (zero) display the message: the character ch not found. Otherwise display the result.
D) At the end of the JavaScript file, finish with this line to fire the load event when a resource and its dependent resources have finished loading:
window.addEventListener( "load", getAllDomElement, false );
Here is my script in the html and js files:
<!DOCTYPE html>
<html lang = "en">
<head>
<title> Assignment3Q1 </title>
<meta charset = "utf-8">
<script type = "text/javascript" src = "CharacterOccurences.js">
</script>
<link rel = "stylesheet" type = "text/css" href = "CharacterOccurences.css"/>
</head>
<body>
<p> Enter some text: <br>
<textarea id = "searchString" rows = "4" cols = "55"></textarea>
</p>
<p> Enter characters to search for: <br>
<input type = "text" id = "characters" size = "5" />
<input type = "button" id = "searchButton" value = "Search" onclick = "getAllDomElement();"/>
</p>
<p id = "output">
</p>
</body>
searchStr = document.getElementById("searchStr");
ch = document.getElementById("characters");
outResult = document.getElementById("output");
function getAllDomElement()
{
document.getElementById("searchButton").addEventListener("click", searchOccurences, false);
searchStr = document.getElementById("searchStr");
ch = document.getElementById("characters");
outResult = document.getElementById("output");
}
function searchOccurences()
{
var count = 0;
var chValue = ch.chartAt(0).toLowerCase();
var searchStr = searchStr.toLowerCase();
var result;
}
window.addEventListener("load", getAllDomElement, false);
You see that I haven't completed the searchOccurences() function. I attempted to go through a for loop and increment count every time I find an occurrence of the letter entered, but nothing gets displayed when I press Search. It's supposed to look like this:
I'm quite new in Javascript. Sorry if I say some absurd. None of the previous answers I found here worked in my case...
The code gets an index from a selected option from a dropdown list generated by an array loop, and uses this index to post description of a product in a textarea. Ideal would be one in each line. But whenever I add '\n'(added only for visualization by the end of the code) or '

'; the dropdown list itself disapears. Trying '< br>' does not work either.
pr[] is a nested array that contains a description of 10 products (ex adidas soccer ball) in its first position and price at the second.
The function buy() is called by a button onclick event, each time it is called it adds one product to the textarea.
Thanks in advance!
textd=" ";
valord=0;
function buy() {
var e = document.getElementsByTagName("select");
var f = e[0].selectedIndex;
textd +=pr[f][0];
valore = valord += pr[f][1];
document.getElementById("compras").value=textd\n;
document.getElementById("valor").value ="R$ "+ valore+",00";
}
You need to add "\n" to the end of the string while adding text to text area, then this "\n" ensures that row will be displayed in a new line instead of same line.
Look at the following code
<!DOCTYPE html>
<html>
<body>
<script>
function appendText()
{
debugger;
var ele = document.getElementById("textArea");
var text = ele.value;
text += "im clicked\n";
text +="clicked again\n";
text +="clicked third time\n";
text +="clicked forth time";
ele.value = text;
}
</script>
<textarea rows="4" cols="50" id="textArea">
At w3schools.com you will learn how to make a website. We offer free tutorials in all web development technologies.
</textarea>
<button type="button" onclick="appendText()">Click me </button>
</body>
</html>
You may need to change your code to
textd +=pr[f][0] + "\n";
document.getElementById("compras").value=textd;