I need to extract the text from a div with paragraphs and spans and other things and put it into a textarea. I need to load just the text, not the HTML.
For that, I can use:
loadtext = $('#mydiv').text();
However, I DO need to retain the line breaks.
For that, I'm doing:
loadtext = $('#mydiv').text().replace(/<br>/gm, '\r\n');
But it doesn't seem to be working, because when I load that text into a textarea, it's all flat with no line breaks. Am I doing something wrong?
$('#mydiv').text() has already been stripped of all HTML, including<br> elements, so this will not work. You need to modify the HTML of the #mydiv element and replace all <br/> elements, then retrieve the text.
$('#mydiv').find('br').each(function(){
$(this).after("\n")
.remove();
});
var loadtext = $("#mydiv").text();
An alternate solution is to use an intermediate element that's never added to the document.
var html = $('#mydiv').html(); // e.g. '<p>line 1</p><br><br><p>line 2</p>'
var text = $('<div>').html(html.replace(/<br\/?>/g, '\n')).text();
/* text =
"line 1
line 2"
*/
$('#mytextarea').text(text);
This supports <br> (HTML) and <br/>(XHTML).
Related
Setting the value of the textarea, won't be reflected in the HTML.
For instance,
If you have <textarea></textarea> in your HTML, and set its value to 'Hello' the HTML will remain unchanged and not <textarea>Hello</textarea>
I think this is what you want, use this to your w3schools example
<script>
function myFunction() {
var x = document.getElementById("myTextarea").value;
document.getElementById("demo").innerHTML = x;
}
myTextarea.onkeyup=()=>myTextarea.innerText=myTextarea.value;
</script>
You seem to be working off some misconceptions. I take it you're expecting that line breaks in the text area will be reflected as line breaks in a paragraph if you insert it as the HTML of the paragraph. In HTML, all whitespace is collapsed into spaces, and line breaks in HTML source do not normally translate to breaks in HTML text flows. If you do want newlines to work in HTML, use a <pre></pre> element instead. Otherwise you'll need to convert newlines to <br> elements.
There's also the white-space CSS style that can change the way that whitespace is rendered.
I have been trying to add some custom features in tinymce editor. A button to highlight a text and the highlighted text should further be replaced with a underscore. This means that the mark element with it content should be replace with something like this:
<p> This yet another moment of trial. We <mark>keep</mark>doing it until it becomes <mark>perfect</mark>.</p>
To this:
<p> This yet another moment of trial. We <b>_____</b>doing it untill it becomes <b>____</b>.</p>
I have been trying it with this function
function getContentFromEditor() {
var content = tinymce.activeEditor.getContent();
content = content.replace("<mark>", "<b>______</b>");
document.getElementById("content_display").innerHTML = content;
}
But it only change the start tag.
This is the regex you need:
/<mark>\[^<>\]*<\/mark>/g
So your code should be updated like this:
content = content.replace(/<mark>[^<>]*<\/mark>/g, "<b>______</b>");
Demo:
This is a sample Demo:
var text = '<p> This yet another moment of trial. We <mark>keep</mark>doing it until it becomes <mark>perfect</mark>.</p>';
text = text.replace(/<mark>[^<>]*<\/mark>/g,"<b>______</b>");
console.log(text);
After making content changes to the tinyMCE editor dynamically you have to call the save function to update it visually.
Depending on your version:
tinymce.triggerSave();
or
tinymce.activeEditor.save();
First, you need to find all the marked elements.
And then loop over all those marked elements and replace them with the target HTML you want the elements to be replaced with
var replaceWithStr = "<b>____</b>";
var markedElems = document.getElementsByTagName("mark");
var markedElemsArr = [].slice.call(markedElems);
markedElemsArr.forEach(function(elem){
//elem.innerText = replaceWithStr; // this will only replace text
//elem.innerHTML = replaceWithStr; // this will not remove the mark tag, so your underscore will still be highlighted
elem.outerHTML = replaceWithStr; // this will give the required result
})
<p> This yet another moment of trial. We <mark>keep</mark> doing it until it becomes <mark>perfect</mark>.</p>
You can try using regular expressions:
content = content.replace(/<mark>[a-zA-Z]*<\/mark>/g,"<b>______</b>");
When pasting data from the clipboard into an html textarea, it does some pretty cool parsing to make the paste look close to what was copied as far as newlines go.
For example, I have the following html on a page that I select (everything highlights in blue) and then I copy it:
Hello
<br>
<br>
<br>
<div>more</div>
<div>last</div>
So to be clear, what I am copying is what the output of this jsfiddle looks like.
Now when I paste this magical, copied text into a text area, I see exactly what I would expect: "Hello", empty line, empty line, empty line, "more", "last". Cool! Then when I use jQuery's .val() on the textarea, I get "Hello\n\n\nmore\nlast". Super cool. It took the br's and div's and was able to infer the correct newlines from it.
Now...
What I am trying to do it programmatically take the same data I copied earlier and set it as the textarea's value as if it were pasted.
Here is what I have tried...
So, say the stuff I copied earlier was wrapped in a <div id="parent">...</div>.
var parent = $("#parent");
var textarea = $("#theTextArea");
// Set the value of the text area to be the html of the thing I care about
textarea.val(parent.html());
Now I know this isn't the same as a copy-paste, but I was hoping it would take care of me and do what I wanted. It doesn't. The textarea gets filled with Hello<br><br><br><div>more</div><div>last</div>. The html that was once invisible is now stringified and made part of the text.
Obviously I did this wrong. .html() returns, of course, the string of html. But is there something I could call on parent that would give me the text with all inferred linebreaks?. I have tried calling parent.text(), but this only gives Hellomorelast (no line breaks).
A few notes that could help with an answer: I am using Angular, so I have access to all their goodies and jQuery.
Edit:
Solution
It is not nice but you can try to replace html tags with line breaks '\n' or do some line breaks in the html file and get the content with text().
var parent1 = $("#paren1");
var textarea1 = $("#theTextArea1");
var parent2 = $("#paren2");
var textarea2 = $("#theTextArea2");
// Set the value of the text area to be the html of the thing I care about
var text = parent1.html();
text = text.replace(new RegExp("<br>", 'g'),"\n");
text = text.replace(new RegExp("<div>", 'g'),"");
text = text.replace(new RegExp("</div>", 'g'),"\n");
textarea1.val(text);
textarea2.val(parent2.text());
JSFiddle
How to remove or hide only visible "text & link" from website using java script. For example I want to hide "some text " & "Link text here" from bellows code without remove this full code
<p style="text-align:center;">some text Link text here</p>
Please help me
Assuming you mean that you want to hide the <p> tag, you need this piece of JavaScript:
document.getElementsByTagName('p')[0].style.display = 'none';
That will hide the first <p> tag on your page. I suggest adding a class or id to the tags you want to hide though, so that you can select them more accurately.
If you want to clear all contents of your <p> tag, you can do this:
document.getElementsByTagName('p')[0].innerHTML = '';
That will simply remove all of the tag's contents. If you want to remove the whole tag itself (so that it doesn't leave the empty <p> tag sitting around) you can change the .innerHTML part to .outerHTML.
There are several things to consider: you may want the test to return, so we cannot just lose it. You may want to preserve event bindings on nested elements, so we cannot simply destroy those. In the end, I would suggest CSS being the most appropriate route to take.
var paragraph = document.querySelector("p");
paragraph.style.overflow = "hidden";
paragraph.style.textIndent = "-1000%";
You could, alternatively, create a custom class meant to set overflow and text-indent, and toggle that class with JavaScript (jQuery?) instead:
paragraph.classList.toggle( "offsetChildren" );
// jQuery: $(paragraph).toggleClass( "offsetChildren" );
Fiddle: http://jsfiddle.net/6UZ82/
Try this code
function Hide(ptext,aText){
var p = document.getElementsByTagName('p');
var a = document.getElementsByTagName('a');
for(var i=0;i<a.length;i++){
if(a[i].innerHTML==aText){
a[i].setAttribute("style","display:none") ;
}
}
for(var i=0;i<p.length;i++){
var str = p[i].innerHTML;
var rp = str.replace(ptext,'<span style="display:none">'+ptext+'</span>');
p[i].innerHTML = rp;
}
}
Hide('some text','Link text here');
Also you can show back using the reverse logic. i have commented out the show function in fiddle. you can uncomment it and click run to see it in action
Demo here
When a user create a message there is a multibox and this multibox is connected to a design panel which lets users change fonts, color, size etc.. When the message is submited the message will be displayed with html tags if the user have changed color, size etc on the font.
Note: I need the design panel, I know its possible to remove it but this is not the case :)
It's a Sharepoint standard, The only solution I have is to use javascript to strip these tags when it displayed. The user should only be able to insert links, images and add linebreaks.
Which means that all html tags should be stripped except <a></a>, <img> and <br> tags.
Its also important that the attributes inside the the <img> tag that wont be removed. It could be isplayed like this:
<img src="/image/Penguins.jpg" alt="Penguins.jpg" style="margin:5px;width:331px;">
How can I accomplish this with javascript?
I used to use this following codebehind C# code which worked perfectly but it would strip all html tags except <br> tag only.
public string Strip(string text)
{
return Regex.Replace(text, #"<(?!br[\x20/>])[^<>]+>", string.Empty);
}
Any kind of help is appreciated alot
Does this do what you want? http://jsfiddle.net/smerny/r7vhd/
$("body").find("*").not("a,img,br").each(function() {
$(this).replaceWith(this.innerHTML);
});
Basically select everything except a, img, br and replace them with their content.
Smerny's answer is working well except that the HTML structure is like:
var s = '<div><div>Link<span> Span</span><li></li></div></div>';
var $s = $(s);
$s.find("*").not("a,img,br").each(function() {
$(this).replaceWith(this.innerHTML);
});
console.log($s.html());
The live code is here: http://jsfiddle.net/btvuut55/1/
This happens when there are more than two wrapper outside (two divs in the example above).
Because jQuery reaches the most outside div first, and its innerHTML, which contains span has been retained.
This answer $('#container').find('*:not(br,a,img)').contents().unwrap() fails to deal with tags with empty content.
A working solution is simple: loop from the most inner element towards outside:
var $elements = $s.find("*").not("a,img,br");
for (var i = $elements.length - 1; i >= 0; i--) {
var e = $elements[i];
$(e).replaceWith(e.innerHTML);
}
The working copy is: http://jsfiddle.net/btvuut55/3/
with jQuery you can find all the elements you don't want - then use unwrap to strip the tags
$('#container').find('*:not(br,a,img)').contents().unwrap()
FIDDLE
I think it would be better to extract to good tags. It is easy to match a few tags than to remove the rest of the element and all html possibilities. Try something like this, I tested it and it works fine:
// the following regex matches the good tags with attrinutes an inner content
var ptt = new RegExp("<(?:img|a|br){1}.*/?>(?:(?:.|\n)*</(?:img|a|br){1}>)?", "g");
var input = "<this string would contain the html input to clean>";
var result = "";
var match = ptt.exec(input);
while (match) {
result += match;
match = ptt.exec(input);
}
// result will contain the clean HTML with only the good tags
console.log(result);