Get selected text with format using javascript - javascript

Basically, I want style of selected text. Suppose, I have a full text "Hello world to sample application" placed in div. Then I made a word "Hello" in bold. I want to retrieve style of word "Hello" word and not of whole div.
There is one method "getCommandValue" method available but not working with Firefox.
"getComputedStyle" method gives style of the object and not of selected text in div.

<div id='mydiv'><span id='boldword'>Hello</span> world to sample application</div>
Then f.e. with jQuery:
$('#boldword').css('font-weight');
.css(attribute) gives you the current value for an attribute, .css(attribute, value) sets a news value for the given attribute.
I hope that's what you meant.

Related

Spaces within javascript .text call

I have one div with a temporal text, once other images are clicked I want to show a different text, for this I'm using the .text on javascript call, I can replace the text, my problem is that I can't create spaces or paragraph breaks. Can someone explain me how to implement it?
$("#memberTrigger").click(function() {
$("#memberDescriptionResponsive").text('This is the Large Description I want to appear within that text area defined previously. After this dot I would like to have a break of paragraph and continue in a secondary one, right now is showing on the same line as continuity');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 id="memberDescriptionResponsive">Some Information of the Team Member</h3>
<div id="memberTrigger"></div>
text is for:
Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
http://api.jquery.com/text/
And you should use html
This method uses the browser's innerHTML property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters http://api.jquery.com/html/
$("#memberDescriptionResponsive").html('<span style="background:red">This is the Large Description</span><br>I want to appear within that text area defined previously. After this dot I would like to have a break of paragraph and continue in a secondary one, right now is showing on the same line as continuity');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="memberDescriptionResponsive">hey</div>
The text method inserts text. Just text. Not elements. If you want an element, then you need to use something else.
First, you need to change the h3 to something different. No HTML heading element is allowed to contain a paragraph.
Then you can use empty to clear the existing content and append to add new elements.
var heading = $("<h3 />").text("This is the Large Description I want to appear within that text area defined previously.");
var paragraph = $("<p />").text("After this dot I would like to have a break of paragraph and continue in a secondary one, right now is showing on the same line as continuity");
$("#memberDescriptionResponsive").empty().append([heading, paragraph]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="memberDescriptionResponsive"><h3>Some Information of the Team Member</h3></div>
You can add <br> in between where you want to add the break. but instead of using text you got to use .html
$("#memberTrigger").click( function() {
$("#memberDescriptionResponsive").html('This is the Large Description<br> I want to appear within that text area defined previously.<br> After this dot I would like to have a break of paragraph and continue in a secondary one, <br>right now is showing on the same line as continuity')});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 id="memberDescriptionResponsive">Some Information of the Team Member</h3>
<div id="memberTrigger">a</div>

How can a DIV act like another element in Javascript?

My skills in Javascript are limited and for practicing i'm trying to programatically fill some elements using JS code, using Chrome's Developer Tools. I navigate to a site, access the console and try to manipulate DOM elements using JS code.
Usually elements a user can input data are INPUT, TEXTAREA , SELECT and so on. But latelly i've been seeing elements that are user-editable, but are simply DIVs. In other words, a DIV acting like an INPUT or TEXTAREA, and this got me confused.
Here is an example : i extracted this source from a page to post topics in a Facebook Group.
Note that the div that has the 'Write something' innerhtml works as a textarea in the page. You can reproduce this code in any Facebook Group, ie https://www.facebook.com/groups/914737511952904/ (you might need to join the group before see the box to post a topic).
<div class="_1mwp _1mwq _5bu_ _5yk1"><div class="_5yk2" tabindex="-2">
<div class="_5rp7">
<div class="_1p1t">
<div class="_1p1v" id="placeholder- 2bc29">Write something... </div>
</div>
</div>
</div>
If this element was a TEXTAREA, i could easily do something like
document.getElementById('elementId').value = 'New text';
But the 'textarea' element in the above case is actually a DIV and nothing else.
How can i insert text on it using JS ? An how can a DIV act like a textarea or an input ?
Thanks !
How can I insert text on it using JS?
That's quite simple. Just use the innerHTML property to assign the text value.
document.getElementById('elementId').innerHTML = "Text inserted"
However you can do the same using just CSS, and then retrieving the text from the div invoking the same property.
How can a DIV act like a textarea or an input?
A very practical way is using the contentEditable property over the div, but you can use CSS styles as well, and in some cases with some JavaScript code.
You have a simple example here using CSS styles and contentEditable property:
https://jsfiddle.net/ThinkingStiff/AbKTQ/
How can I insert text on it using JS?
element.textContent = "text content"
SNIPPET 1
var div = document.querySelector('div');
div.textContent = "line of text by textContent"
<div></div>
An how can a DIV act like a textarea or an input?
You can add contneteditable to an element that's not originally editable.
<div contenteditable></div>
See Snippet on how to set contenteditable by JS
SNIPPET 2
var editor = document.querySelector('div');
editor.setAttribute('contenteditable', true);
<div>This is a div. Click on me and start typing.</div>

Javascript to fill a formatted text field on a web site

I know virtually nothing about Javascript. By a monkey-see, monkey-do approach I’ve managed to successfully use Javascript within AppleScript/Safari to fill text fields on a web-site using the following command:
do JavaScript "document.getElementById('ElementID').value ='TextToEnter';" in document 1
I’ve been able to enter text into all fields except one. The fields that work are labeled as input type="text”. The field that doesn’t work is complex in that the entered text can be formatted (bold, italics, underline, alignment, etc.) after entry. Assuming I’ve identified the correct source code for this element it looks as follows PRIOR TO any text entry:
<body id="tinymce" class="mce-content-body " onload="window.parent.tinymce.get('fax_text').fire('load');" contenteditable="true" spellcheck="false"><p><br data-mce-bogus="1"></p></body>
Depending on how its viewed, sometimes the p and br tags appear on separate lines but everything is otherwise identical.
After manual entry of text (“INSERT TEXT HERE”) directly into the web page's text field the source code becomes:
<body id="tinymce" class="mce-content-body " onload="window.parent.tinymce.get('fax_text').fire('load');" contenteditable="true" spellcheck="false"><p>INSERT TEXT HERE</p></body>
The following did not work (wrapped in Applescript):
document.getElementById('tinymce').value ='INSERT TEXT HERE';
It produces the error: "missing value".
As per #WhiteHat, the following with n= 0-4 inserted text at several spots on the page but not in the targeted text field; n > 4 resulted in the "missing value" error:
document.getElementsByTagName('p')[n].innerHTML ='Insert text here';
I tried targeting the br tag but to no avail. How do I target this text field with Javascript? Note: I do not need to format the entered text.
You need to access the <p> element, which is just after the body of the document, as such...
document.getElementsByTagName('P')[0].innerHTML = 'your text'
The getElementsByTagName function returns an array of all elements with the tag name you provide, P in this case. You're looking for the first one, hence the [0].
The innerHTML property will allow you to set the contents of the <p> element.
Following is a good JavaScript reference...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
The following reference is for the web page, or Document Object Model (DOM).
https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model
And tinymce is a 3rd party JavaScript library which allows the rich edit functionality.
http://www.tinymce.com/
Based on the comments, the specific field you are looking for is named fax_text. Here is the source, it's in a textarea tag, take note on which function to use TagName vs. Name...
document.getElementsByName('fax_text')[0].value = 'This is my text!';
document.getElementsByTagName('textarea')[0].value =
document.getElementsByName('fax_text')[0].value +
'\nThis is additional text...';
<textarea rows="5" name="fax_text" cols="36" class="mytext"></textarea>
This text field is in an iFrame.
This iFrame contains an HTML document (<html><head><body>).
To get this document, you need the_iFrame.contentDocument.
do JavaScript "var ifr = document.getElementById('fax_text_ifr'); ifr.contentDocument.getElementsByTagName('p')[0].innerHTML = 'some text';" in document 1

Hightlight substring of "text" in HTML SELECT OPTION using javascript

I have a html-select which gets populated at run time.
i.e. when i type something in html input textbox, i display the substring based results in below attached html-dropdown-listbox.
Now i want to highlight only that substring of an item in html dropdown listbox which matches with the string in html-input textbox.
e.g.
if i type "ample" in html-input textbox then it should highlight "ample"
<OPTION value=723.1> S*ample* Text </OPTION>
i have already tried to modify the innerHTML property of that html-dropdown-listbox.
I want to do it using javascript.
You cannot style the inside elements of a SELECT. It's rendered by the OS, not HTML.
Try this approach
<p id="textindrop">this is the text in the dropbox</p>
tohighlight
<script type="text/javascript">
function highlightsubstring(el) {
var theText = document.getElementById(el).innerHTML;
theText = theText.replace(/(web)/gi, "<b>$1</b>");
document.getElementById(el).innerHTML = theText;
}
</script>
Try this and see this helps you, put some logic of yours also. you can also use regular expressions for this. read about regular expression in javascript
There is a CSS3 way:
Use font-family: monospace to get equal width characters.
Use background-image to get an adjustable background.
Use background-position to set the starting position of the highlighting background in ch.
Use background-size to set the length of the highlighting background in ch.
Restrictions:
Only works in Gecko-based browsers.
Highlighting in the select too requires additional adjusting. (I did it with text-indent, finding better solution is encouraged.)
I put together a simple demo on jsFiddle.

Script to change value of a text - Javascript

From this question i came to know text element's value can be changed by JS Set maximum number of item in Select List - html
can anyone give some code or some tips ?
My intention is not hacking, i need to know this, coz i'm writing a web app where most of the validation is done by JS
Edit
Looking for guide on running JS from client side on a page served by a server [on some text where it's readonly="true" ] !
For example, if you have a html text element like this:
<p id="textelement">I am a text element</p>
You can change the text inside with JS like this:
<script type="text/javascript">
document.getElementById("textelement").innerHTML = "New text inside the text element!";
</script>
You can use this technique with any HTML element which can contain text, such as options in a select list (<option> tag). You can select elements in other ways:
getElementById() Accesses the first element with the specified id
getElementsByName() Accesses all elements with a specified name
getElementsByTagName() Accesses all elements with a specified tagname
More info here.
PS - If you want to change the value of an element's attribute, and not its inner text, you should use the setAttribute() method; for example, if you have:
...
<option id="optionone" value="red">Nice color</option>
...
and want to change the value attribute, you should do:
<script type="text/javascript">
document.getElementById("optionone").setAttribute("value", "green");
</script>
More about this here.

Categories