Appending HTML-encoded string as HTML, not as text - javascript

I'm trying to append this string:
<div> hello </div>
as an HTML node, but instead of appending HTML it just appends the text:
<div> hello </div>
How do I make jQuery append this as an HTML node, not just text?
I'd like a solution that works both for nested divs AND text, if possible.

// This is your string :)
var myString = "<div> hello </div>";
// This is a way to "htmlDecode" your string... see link below for details.
myString = $("<div />").html(myString).text();
// This is appending the html code to your div (which you don't have an ID for :P)
$("#TheDivIWantToChange").append(myString);
HTML-encoding lost when attribute read from input field

You can create a new div with .createElement('div'). Then simply change the new element's HTML.
$(document.createElement('div').html('<p>All new content.</p>'));
To attach the new element to the DOM either use element.append() or .appendTo(element) to append to your element of choice.

Maybe this is a bit verbose, but this is usually how I handle stuff like that:
var div = $(document.createElement("div"));
div.text(" hello "); //Or div.html(" hello ") if need be...
$("#divtoappendto").append(div);

Related

How to set an "id" to a tag using the execCommand in Javascript?

I am trying to make up a basic text editor, and I used execCommand a lot for this.
However, I want to create a heading in such a way, so that whenever user will click on the heading button(in text editor), the execCommand will make up a new heading and should add id to the newly created heading, so that, later I can create interlinks in document with just a single click.
Let say my input in for heading text editor is:
Create a heading with id
I've tried this to create a heading with id:
document.execCommand('formatBlock', false, header).id = userSelection;
HTML output for this:
<h3>Create a heading with id</h3>
As you can see, the id is not added to the HTML output, so how can I add an id to it?
I've also tried this link but didn't get much:
How to add class or id or CSS style in execCommand formatBlock 'p' tag?
Please help :)
EDIT :
Well, I got a hack to do this:
We can add the id to the newly created tag by using the Query selector so that whenever I will create a new tag using execCommand, I will find that tag by selecting the main div(in which editing is going on), and after finding that header tag, I can simply add the id to it.
Like I used this to create a header tag in div(contenteditable="true"):
document.execCommand('formatBlock', false, header);
And to add 'id' to this newly created tag, use this:
let elemMain = $("#editor " + header);
// this will find the div with id="editor" and then find the header tag inside it.
elemMain[elemMain.length - 1].id = userSelection;
//this will add an id to the last header tag inside of div.
Well, this is just a hack to get work done, but if anyone finds out a direct way to add 'id' to tag using execCommand then most welcome :)
Adding id attribute to the <body> tag here using execCommand.
Using javascript :
var idValue = "body-element";
document.execCommand(document.body.setAttribute("id", idValue));
Using jquery :
var idValue = "body-element";
document.execCommand($('body').attr('id', idValue));
Working snippet for newly created element:
var para = document.createElement("p");
var node = document.createTextNode("This is newly created paragraph ( inspect this element and see the id.)");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
var idValue = "new_id";
document.execCommand(para.setAttribute("id", idValue));
<html>
<body>
<div id="div1">
<p id="p1">This is an old paragraph.</p>
</div>
</body>
</html>
Had the same requirement to use document.execCommand to manipulate a contenteditable element, and eventually resorted to the innerHTML option of execCommand. For example...
document.execCommand("insertHTML", false, "<div id='myId'>Hello World!</div>")
...adds the specified HTML at the insertion point, leaving the HTML element addressable by myId. The drawback to this technique is that one has to construct the HTML string. An alternative is to employ the createElement function, and then reference the outerHTML of the element node when calling execCommand...
let elemNode = document.createElement('div')
elemNode.id = 'myId'
elemNode.innerText = 'Hello World!'
document.execCommand('insertHTML', false, elemNode.outerHTML)
Note that I only tested this on Chrome.
Hope this helps anyone else finding this nook of the internet.

Javascript : Replace Detect a string and replace html in a div after changing color

I am trying to change color of a part of strings. I have a list of DOM elements, and for each of them, the text can contain some hashtags. I would like to put in color all hashtags words which could be found in the text.
Here is the begin of the code :
var listOfText = document.getElementsByClassName("titleTweet");
for (var nodetext in listOfText) {
var divContent = listOfText[nodetext].innerHTML;
if (divContent.indexOf("#") !== -1) {
// Do job here
}
}
For example, divContent can be equals to "Hello my #friends ! How are you ?"
I would like to update the dom elements to put in red color the word "#friends".
I don't know how to do that using javascript or jQuery.
You can use a regexp to find the hastags and wrap them with html. Then use the .html() method to replace the original element's html with the new string.
Example snippet
$('#myDiv').replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
Working example - http://jsfiddle.net/4p4mA/1/
Edited the example to work on all divs on the page.
Note: This will only work so long as your element only contains text, because it is replacing all the child nodes with its text value.
use regex for this, find text having hashtag and replave that in span tag for each element.
$('.titleTweet').each(function(){
var $this=$(this);
$this.html($this.text()
.replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
});
See demo here
.innerHTML is a poor basis to starting replacing text. You'll want to navigate down to the text nodes and use .nodeValue to get the text. Then you can start splitting up the text nodes.

extracting text from html file

I'm trying to get nodes containing text from html file using Javascript and jQuery.
if I have a node like
`
<div>txt0
<span>txt1</span>
txt2
</div>
How can I select elements that meets this criteria??
Meaning, I need to retrieve thedivand thespan` , and it would be even better to know location of the text.
I'm trying to get the text to replace it with images in a later function.
I tried this
`
$('*').each(function(indx, elm){
var txt = $(elm).text();
// my code to replace text with images here
});
`
but it does not get the required results.. it does all the parsing in the first element, and changes the html totally.
I don't know exactly what you're trying to solve, but perhaps you can be a bit more specific with your selector?
$("div span").text(); // returns 'txt1'
$("div").text(); // returns 'txt0txt1txt2'
By adding ids and/or classes to your html, you can be very specific:
<div class="name">Aidan <span class="middlename">Geoffrey</span> Fraser</div>
...
// returns all spans with class
// "middlename" inside divs with class "name"
$("div.name span.middlename").text();
// returns the first span with class
// "middlename" inside the fourth div
// with class "name"
$("div.name[3] span.middlename[0]").text();
JQuery has pretty good documentation of these selectors.
If this doesn't help, consider explaining the problem you're trying to solve.
Your markup structure is a bit uneasy. Consider changing to something like this
<div>
<span>txt0</span>
<span>txt1</span>
<span>txt2</span>
</div>
Then using jQuery
$("div span").each(function(k,v) {
$(this).html("<img src=\""+v+".jpg\" />"); //replace with the image
});

Find Html Inside a String Using Jquery

I am not sure how practical this question is , but what i am trying to do is find html inside a string and then append pre tags to it using jquery. let say i have a variable with following string.
var string = "Some normal text <html><body><div> This is the html </div> </body></html>";
Html inside the string is dynamic and can contain any tags , what i want is to find the starting and ending of html and append,prepend pre tags accordingly.
Thanks
The following code does pretty much what you want, however it does not allow html, body tags etc. But those are not allowed in pre tags anyway.
var string = "Some normal text <html><body><div> This is the html </div> </body></html> more text<p>more html content</p>";
var holder = $('<div>').html(string);
holder.children().wrap('<pre>');
//Print result to console
console.log(holder.html());
Also a jsFiddle here: http://jsfiddle.net/evBCm/1/
Add the text to dynamic html tag e.g span or div and find desired node e.g
var string = "Some normal text <html><body><div> This is the html </div> </body></html>";
$("<span/>").html(string).find('div')
Apply bellow regix..
var string = "Some normal text <html><body><div> This is the html </div> </body></html>";
var iMatches = string.match("<html>(.*)</html>");
var iHtml='<html>'+iMatches[1]+'</html>';
alert(iHtml);

javascript: extracting text from html

I am getting html content as below:
var test='<div id="test">Raj</div>';
How can i retrieve value Raj from above html content using javascript.
It sounds like you're trying to extract the text "Raj" from that HTML snippet?
To get the browser's HTML parser to do your dirty work for you:
// create an empty div
var div = document.createElement("div");
// fill it with your HTML
div.innerHTML = test;
// find the element whose text you want
test = div.getElementById("test");
// extract the text (innerText for IE, textContent for everyone else)
test = test.innerText || test.textContent;
Or in jQuery:
test = $(test).text();
If you use jQuery (I cannot believe I just said that ;)) you can get at the content immediately you wrap it in $(test).html
Someone else will tell you how to get at the innerHTML using a selector since everybody here are jQuery gurus but me
Update: somebody just did while I was editing: javascript: extracting text from html - see comments or updates to that
var test = getElementById('test')
try that

Categories

Resources