Select Particular Text in HTML Element

How to select text inside an HTML element, based on content?

Filter your list with filter.

let courses = e.filter(item => item.textContent === "Course");

This is using let and fat arrow syntax aka a lambda which are ES6 syntax. If you want ES5 JavaScript, simply use var and a normal anonymous function.

var courses = e.filter(function(item) {
return item.textContent === "Course";
});

Edit: Kevin B spotted that my function will be undefined and he his right. That is because e is a NodeList and not an array. We have to convert it! There are multiple ways to convert a NodeList to an array. The easiest being splice. Or you can get fancy and use spread syntax [...e].filter or Array.from() as well, which are both also ES6 features.

Selecting text in an element (akin to highlighting with your mouse)

Plain Javascript

function selectText(nodeId) {
const node = document.getElementById(nodeId);

if (document.body.createTextRange) {
const range = document.body.createTextRange();
range.moveToElementText(node);
range.select();
} else if (window.getSelection) {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(node);
selection.removeAllRanges();
selection.addRange(range);
} else {
console.warn("Could not select text in node: Unsupported browser.");
}
}

const clickable = document.querySelector('.click-me');
clickable.addEventListener('click', () => selectText('target'));
<div id="target"><p>Some text goes here!</p><p>Moar text!</p></div>
<p class="click-me">Click me!</p>

Select specific text of an HTMLElement

It works exactly for your example. The function retrieves the Text node from the given Element node, so mind that if the given element contains Element children (rather than direct text content) you have to adjust that function to your need.

const el = document.getElementById('my-text-element');
selectWord(el, 'world');

function selectWord(element, word){
const textNode = element.childNodes[0]; //retrieve the Text node from the Element node
const selection = window.getSelection(); //get the Selection object
const range = document.createRange(); //create the Range object
const text = textNode.textContent; //retrieve the [string] from Text object
const startPosition = text.search(word); //now we look for the word in the [string] value
if(startPosition === -1) return; //if the word does not exist return and do nothing
const endPosition = startPosition + word.length; //we need start and end position to select the found word
range.setStart(textNode, startPosition); //it takes the Text node within we want to select some text, and we pass the starting character
range.setEnd(textNode, endPosition); //we pass the ending character in the same Text node
selection.addRange(range); //pass our prepared Range object and select the text
}
<p id="my-text-element">hello world</p>

Selecting all text in HTML text input when clicked

You can use the JavaScript .select() method for HTMLElement:

<label for="userid">User ID</label>
<input onClick="this.select();" value="Please enter the user ID" id="userid" />

Selecting a portion of text in html Using Java

It's not possible to do that with pure CSS selectors, additional extracting and appending logic in Java code needed:

  1. Select pre element
  2. Split it to sequence of text parts by a element as splitter.
  3. Skip 1st element and join two (or more) next parts.

Here simple code sample for that (JDK 1.8 style with stream API and old JDK 1.5 - 1.7 style):

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;

import static java.util.Arrays.stream;
import static java.util.stream.Collectors.joining;

public class SimpleParser {
public static void main(String[] args) throws IOException {
final Document document = Jsoup.parse(new File("div.html"), "UTF-8");
final Elements elements = document.select("div.pane.big pre");

System.out.println("JDK 1.8 style");
System.out.println(
stream(elements.html().split("\\s+<a.+</a>\\s+"))
.skip(1)
.collect(joining("\n")
));

System.out.println("\nJDK 1.7 style");
String[] textParts = elements.html().split("\\s+<a.+</a>\\s+");
StringBuilder resultText = new StringBuilder();
for (int i = 1; i < textParts.length; i++) {
resultText.append(textParts[i] + "\n");
}
System.out.println(resultText.toString());
}
}

P.S. Note that last tag div in your HTML code sample should be closed-tag.

CSS allow text selection within an element only

Apply the style user-select: none on #one like this:

#one {
user-select: none;
}
<div>
<div id="one"> some content will be here... </div>
<div id="two"> text should be select from this div only.. </div>
</div>


Related Topics



Leave a reply



Submit