I am using .text() to add to a div. I don't know how much I will be adding. But if I use .text() more then once it will just add the last one. I have used .text(msg1,msg2,msg3) and this does work for me, but i would like it if the text was more ordered. like after every msg a new line would start. I have tried to add spaces but that does not work and is not the way i want it. I just had a div, i tried adding, <p>'s to it, i tried $("p:first") tried by ID. I have included a fiddle.
http://jsfiddle.net/G24aQ/12/
if(k1<10){
msg1= "This will not space like a want." + " "
msg2= "I don know why not. "
msg3= "How come. "
$('#output1').text(msg1);
$('#p').text(msg2);
$('#output1').text(msg3+" "+msg2+" "+ msg1);
}
You can you use <br/> to add the messages in new lines.
You can use html instead of text and add it all at once. To add one by one, use html and append together.
Demo : http://jsfiddle.net/G24aQ/14/
if (k1 < 10) {
msg1 = "This will not space like a want.<br/>";
msg2 = "I don know why not.<br/>";
msg3 = "How come.<br/>";
$('#output1').html(msg3 + msg2 + msg1); //this will add all the three variables together into #output1 - replacing older content
/*
//To add one by one
$("#output1").html(msg3); // this will erase the older content so that you have a clean #output1 div
$("#output1").append(msg2); //this will add to the existing content, will not over write it
$("#output1").append(msg1); //this will add to the existing content, will not over write it
*/
}
Always keep in mind that html() & text() will erase everything in the selector and add the new content into it. append adds to the existing content. And, your HTML tags will be ignored if text() is used.
Docs for html & append for extra info.
You need to use $(id).append (code); if you want to append, not to change.
As far as i remember, html will only render excessive spaces as one.
You have to use
or put each text inside a span tag with a right margin
<span style="margin-right:10px"></span>
You should use append for that, like:
if (k1 < 10) {
msg1 = "This will not space like a want.<br/>";
msg2 = "I don know why not.<br/>";
msg3 = "How come.<br/>";
$('#output1').append('<p>'+msg1+'</p>'+'<p>'+msg2+'</p>'+'<p>'+msg3+'</p>');
}
and use a html tag like <p> to make them appear in new lines.
You can also do it this way:
if (k1 < 10) {
msg1 = "This will not space like a want.<br/>";
msg2 = "I don know why not.<br/>";
msg3 = "How come.<br/>";
var e = $('<p>'+msg1+'</p>'+'<p>'+msg2+'</p>'+'<p>'+msg3+'</p>');
$('#output1').append(e);
}
Related
I have a content that contains a string of elements along with images. ex:
var str= <p><img src=\"v\">fwefwefw</img></p><p><br></p><p><br></p>
the text that is within the < and > is a dirty tag and I would like to remove it along with the content that is within it. the tag is generated dynamically and hence could be any tag i.e <div>, <a>, <h1> etc....
the expected output : <p></p><p><br></p><p><br></p>
however with this code, im only able to remove the tags and not the content inside it.
str.replaceAll(/<.*?>/g, "");
it renders like this which is not what im looking for:
<p>fwefwefw</p><p><br></p><p><br></p><p><br></p>
how can I possibly remove the & tags along with the content so that I get rid of dirty tags and text inside it?
fiddle: https://jsfiddle.net/3rozjn8m/
thanks
A safe way is to use a DOM parser, visiting each text node, where then each text can be cleaned separately. This way you are certain the DOM structure is not altered; only the texts:
let str= "<p><img src=\"v\">fwefwefw</img></p><p><br></p><p><br></p>";
let doc = new DOMParser().parseFromString(str, "text/html");
let walk = doc.createTreeWalker(doc.body, 4, null, false);
let node = walk.nextNode();
while (node) {
node.nodeValue = node.nodeValue.replace(/<.*>/gs, "");
node = walk.nextNode();
}
let clean = doc.body.innerHTML;
console.log(clean);
This will also work when you have more than one <p> element that has such content.
Remove the question mark.
var str= "<p><img src=\"v\">fwefwefw</img></p><p><br></p><p><br></p>";
console.log(str.replaceAll(/<.*>/g, ""));
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);
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).
quick question, i know we can change the content of a
<div id="whatEverId">hello one<div> by using:
document.getElementById("whatEverId").innerHTML="hello two";
now, is there a way I can ADD stuff to the div instead of replacing it???
so i can get
<div id="whatEverId">hello one hello two<div>
(using something similar of course)
<div id="whatever">hello one</div>
<script>
document.getElementById("whatever").innerHTML += " hello two";
</script>
Notice that using element.innerHTML += 'content' would empty inputs and textareas to their default, blank state, unclick checkboxes, as well as removing any events attached to those elements (such as onclick, on hover etc.) because the whole innerHTML would be reinterpreted by the browser, which means .innerHTML is emptied and filled again from scratch with the combined content.
If you need to keep the state, you'd need to create a new element (a <span> for instance) and append it to the current element, as in:
let newElement = 'span'
newElement.innerHTML = 'new text'
document.getElementById('oldElement').appendChild(newElement)
document.getElementById("whatEverId").innerHTML = document.getElementById("whatEverId").innerHTML + "hello two" + document.getElementById("whatEverId").innerHTM ;
What jcomeau_ictx suggested is an inefficient way of editing the innerHTML.
Check Ben cherry's PPT http://www.bcherry.net/talks/js-better-faster
The correct way will be detaching the element and making changes to it and then appending it back to the parent node.
Use https://gist.github.com/cowboy/938767 Native javascript from this gist to
detach element.
If you are appending, you can just change your = to a +=
document.getElementById("whatEverId").innerHTML += 'hello two';
If prefixing
document.getElementById("whatEverId").innerHTML = 'hello two' + document.getElementById("whatEverId").innerHTML;
Although I would highly recommend using jQuery or MooTools javascript libraries/frameworks to do this sort of thing. If you're adding tags not just text nodes, then you should use the DOM createElement or one of the aforementioned libraries/frameworks.
You can do it by appending div string like this..
document.getElementById('div_id').innerHTML += 'Hello Two';