How to wrap with <p> in first line of contenteditable div - javascript

I used below code to wrap <p> instead of <div>.
document.execCommand('defaultParagraphSeparator', false, 'p')
But I still can't wrap first line, like this "aaa".
<div id=“body-text” class=“body-text” contenteditable=“true” data-placeholder=“Body Contents">
aaa
<p>bbb</p>
<p>ccc</p>
</div>
Does anyone know how to wrap first line "aaa" with <p>?
postscript
I changed my cord using one of the answer for reference.
But now I cant type any letter. Only if I press enter first, it works. But after I press enter and make <p>, I cant type any letter again.
Where is the problem?
<div id='body-text' class='body-text' contenteditable=true data-placeholder='Body Contents' onkeydown={firstLine}></div>
<script>
firstLine(e) {
if(e.keyCode == '13') {
var div = document.getElementById('body-text')
var text = div.firstChild.textContents
div.removeChild(div.firstChild)
var p = document.createElement('p')
p.textContent = text
div.insertBefore(p, div.firstChild)
}
}
</script>

I'm using element.firstChild to select the "aaa" textNode, and creating the paragraph element which then gets prepended back into .body-text.
var pElement = document.createElement('p');
var bodyText = document.querySelector('.body-text');
var firstLine = bodyText.firstChild;
pElement.appendChild(firstLine);
bodyText.prepend(pElement);
console.log(bodyText.outerHTML)
<div class="body-text" contenteditable="true" data-placeholder="Body Contents">
aaa
<p>bbb</p>
<p>ccc</p>
</div>
note: you don't need a class and an ID... choose one

Ok, first I have to let you know that the code you provided was using those fancy quotes “ and ” you must use either this " or this '. Having said that, I have made a Snippet that uses formatBlock.
Highlight the text and click the button <p/>.
It can wrap text in a <p>, <div>, <blockquote>, <h1>, etc..
SNIPPET
<div id="body-text" class="body-text" contenteditable="true" data-placeholder="Body Contents">
aaa
<p>bbb</p>
<p>ccc</p>
</div>
<input type="button" class="p" onclick="document.execCommand('formatBlock', false, 'p')" value="<p/>" title="Insert a Paragraph Wrapped on Highlighted Text">

One way to do it is to get first text node of your div, save the text, remove that node and then create a p tag with the text from your ancient node and insert it in your div.
UPDATED
you had a little typpo problem var text = div.firstChild.textContents, there is no s it only var text = div.firstChild.textContent
see fiddle: https://jsfiddle.net/2rgLzkyj/
HTML :
<div id='body-text' class='body-text' contenteditable=true data-placeholder='Body Contents'>
aaa
<p>bbb</p>
</div>
Javascript:
var div = document.getElementById('body-text')
div.addEventListener('keydown', onKeyDown);
function onKeyDown(e) {
if (e.keyCode == '13') {
var text = div.firstChild.textContent;
div.removeChild(div.firstChild);
var p = document.createElement('p');
p.textContent = text;
div.insertBefore(p, div.firstChild);
}
}

Related

How do I make text bold after the user clicks a button?

I am trying to make a text editor in JavaScript and it has various features like bolding the text and italics and some others. When the user clicks on any one of them, then anything that they have selected will become edited accordingly. Now I am able to get the selected text and even put strong tags before and after the text but when I do it the text doesn't get bold only the tags are seen. How can make the text bold? I sorry but I am unable to provide code since its too much and too messy. Thanks for reading query! Also if you know any JavaScript library which could help me solve this problem then you can suggest me.
document.getElementById("button").addEventListener("click",
() => {
let text = document.getElementById("text").innerText
let selection = window.getSelection();
let boldText = "<strong>" + selection + "</strong>"
document.getElementById("text").innerText = text.replace(selection, boldText)
})
<div id="text">
The dog barks and runs around.
</div>
<button id="button">Make selected text bold</button>
I am using inner text instead of inner html in order to reproduce the problem
You are using innerText to replace which is wrong as we want to change html so use innerHTML.
Code:
document.getElementById("button").addEventListener("click",
() => {
let text = document.getElementById("text").innerText
let selection = window.getSelection();
let boldText = "<b>" + selection + "</b>"
document.getElementById("text").innerHTML = text.replace(selection, boldText) //use innerhtml instead of innertext
})
<div id="text">
The dog barks and runs around.
</div>
<button id="button">Make selected text bold</button>
Here is some code that I used to change to inputted text on a button click
<input type="text" id="sign" value="">
<p style = "font-family: 'Dancing Script', cursive; font-size:50px;"
id="signOutput"></p>
<button onclick="signFunction()">Output Signature</button>
<script>
function signFunction() {var x = document.getElementById("sign").value;
document.getElementById("signOutput").innerHTML = x;
}
</script>
<p id="mypar">Hello</p>
<br>
<button type="button" onclick="changeStyle()">Click Me</button>
<script>
function changeStyle(){
var element = document.input
var element = document.getElementById("mypar");
element.style.fontWeight = "bold";
}
</script>

Get text of div

I want to get the text of the next id (the text is: "Show More").
<div id="show_more_less" onclick="Show_More_Less();">Show more</p>
function Show_More_Less() {
var str = document.getElementById('show_more_less').text;
}
I tried: .value but it doesn't work.
To get the text of an element in a cross browser way, you can do this :
var e = document.getElementById('show_more_less');
var text = e.textContent || e.innerText;
Try innerHTML:
var str = document.getElementById('show_more_less').innerHTML;
Also you have an opening <div> tag and a closing </p> tag which is inconsistent. You probably meant:
<div id="show_more_less" onclick="Show_More_Less();">Show more</div>
Should make some checks to see if childNodes[0] exists and if it's a text node, but basically:
var str = document.getElementById('show_more_less').childNodes[0].nodeValue;

javascript with jQuery - how to change specific Text

How can i change followed given HTML code via javascript and jQuery:
<div> <strong> unimportant text here </strong> important text here </div>
Goal is to change the Text in the <div> .... important text here </div> without touching the ...
<strong> unimportant text here </strong>
...part
Example:
*unimportant text here * important and changed text here
jsFiddle Demo
This requires having access to the parent div. I am not sure how you would like to access it, but for example, I will use an id.
<div id="d"> <strong> unimportant text here </strong> important text here </div>
This allows for the inner element to targeted. You should just use substring in order to select the latter part of the text
var AllText = $('#d').text();
var StrongElementText = $('#d strong').text();
var ImportantText = AllText.substr(StrongElementText.length);
Edit
With no way to target the element directly, it will have to be inferred (which can lead to target collision)
jsFiddle Demo Using Inferred target
$('div strong').each(function(){
var AllText = this.parentNode.innerText;
this.parentNode.innerText += " And Changed";
var StrongElementText = this.innerText;
var ImportantText = AllText.substr(StrongElementText.length);
c[0].innerHTML += ImportantText + "<br>";//shows output
});
<div>
<strong> unimportant text here </strong>
<span id="changeText">important text here</span>
</div>
$('#changeText').text= "I CHANGE THE TEXT";

Parsing specific HTML tags in Javascript

I'm looking for the Javascript to parse the following HTML:
<p>random text random text random text random text</p>
<kbd><h2>Heading One</h2>Body text Body text Body text Body text</kbd>
<p>random text random text random text random text</p>
... and return just:
Heading One
In other words, I'd like to strip all tags and Body Text from within the <kbd> tags.
Any ideas would be greatly appreciated!
var input = /* that HTML string here */;
var div = document.createElement('div');
div.innerHTML = input;
var h2 = div.getElementsByTagName('h2')[0];
var text = h2.innerText || h2.textContent;
alert(text); // alerts "Heading One"
Reference:
document.createElement
innerHTML
element.getElementsByTagName
Node.textContent (Quirksmode compatibility table)
Demo:
http://jsfiddle.net/mattball/vaVPF/
Regex?
var s = "<p>random text</p>\n" +
"<kbd><h2>Heading One</h2>Body text</kbd>\n" +
"<p>random text</p>";
s.match(/<h2>(.*?)<\/h2>/)[1] // == "Heading One"
This matches group one as the shortest possible (.*?) string between <h2>...</h2>.
You can find all matches using the g option.
s.match(/<h2>(.*?)<\/h2>/g) // == ["<h2>Heading One</h2>"]
Note that groups are not accessible.
For multiline content between tags, use
s.match(/<tag>[\s\S]*?<\/tag>/ig)
if you include jquery (jquery.com) you can do this:
var heading=$("h2").html();

jQuery find and replace string

I have somewhere on website a specific text, let's say "lollypops", and I want to replace all the occurrences of this string with "marshmellows". The problem is that I don't know where exactly the text is. I know I could do something like:
$(body).html($(body).html().replace('lollypops', 'marshmellows'));
This would probably work, but I need to rewrite as little HTML as I can, so I'm thinking something like:
search for the string
find the closest parent element
rewrite only the closest parent element
replace this even in attributes, but not all, for example replace it in class, but not in src
In example, I would have structure like this
<body>
<div>
<div>
<p>
<h1>
<a>lollypops</a>
</h1>
</p>
<span>lollypops</span>
</div>
</div>
<p>
<span class="lollypops">Hello, World!</span>
<img src="/lollypops.jpg" alt="Cool image" />
</p>
<body>
In this example, every occurrence of "lollypops" would be replaced, only <img src="... would remain the same and the only elements that would actually be manipulated would be <a> and both <span>s.
Does anybody know how to do this?
You could do something like this:
$("span, p").each(function() {
var text = $(this).text();
text = text.replace("lollypops", "marshmellows");
$(this).text(text);
});
It will be better to mark all tags with text that needs to be examined with a suitable class name.
Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.
You could do something this way:
$(document.body).find('*').each(function() {
if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
$(this).removeClass('lollypops');
$(this).addClass('marshmellows');
}
var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
var text = $(this).text(); //getting just current node text
text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
$(this).text(text); //setting text
$(this).append(tmp); //re-append 'foundlings'
});
example: http://jsfiddle.net/steweb/MhQZD/
You could do something like this:
HTML
<div class="element">
<span>Hi, I am Murtaza</span>
</div>
jQuery
$(".element span").text(function(index, text) {
return text.replace('am', 'am not');
});
Below is the code I used to replace some text, with colored text. It's simple, took the text and replace it within an HTML tag. It works for each words in that class tags.
$('.hightlight').each(function(){
//highlight_words('going', this);
var high = 'going';
high = high.replace(/\W/g, '');
var str = high.split(" ");
var text = $(this).text();
text = text.replace(str, "<span style='color: blue'>"+str+"</span>");
$(this).html(text);
});
var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);
Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.
HTML:
<div>
<div>
<p>
<h1>
<a class="swapText">lollipops</a>
</h1>
</p>
<span class="swapText">lollipops</span>
</div>
</div>
<p>
<span class="lollipops">Hello, World!</span>
<img src="/lollipops.jpg" alt="Cool image" />
</p>
jQuery:
$(document).ready(function() {
$('.swapText').text("marshmallows");
});

Categories

Resources