Remove tag and content using Javascript - javascript

What I want is to get the content of a specific #id, remove a few tags and its contents, add some html before and after it, and then set that finished content as the body content.
I now have the following code, containing a mixture of Javascript and jQuery, although obviously not the right one - resulting in a [object Object]-message.
My code looks like this:
var printContents = jQuery("#"+id).clone();
var printContentsBefore = '<html><head></head><body><table><tr>';
var printContentsAfter = '</tr></table></body></html>';
var mainContents = printContents.find(".td_print").remove();
document.body.innerHTML = printContentsBefore + mainContents + printContentsAfter;
Any ideas of how to make this work?

Your code does not convert the cloned jquery object to a string. Modify your code as follows:
document.body.innerHTML = printContentsBefore + mainContents.html() + printContentsAfter;
Beware that the .html method output will not include the html representation of the container element itself (ie. of the #id clone in your case).

Related

Prevent jQuery from downloading resources when parsing HTML string

var strHTML = "<div><img src='/fake/path/fakeImage.jpg'/><span id='target'>text to extract</span></div>";
var dom = $(strHTML);
var extractedText = dom.find("#target").text();
alert(extractedText);
When I convert the HTML string to a jQuery object, jQuery makes GET request to retrieve pictures as you can see in the network tab in the developer tools.
JsFiddle
How can I convert a HTML string to jQuery object without downloading any resources from the parsed string ?
Note : jQuery.parseHTML does not return a jQuery object, you cannot use .find() for example.
I don't think this is possible, since its not jQuery (or javascript) that does the image loading but the browser - as soon as a src attribute is set on an img element the browser will attempt to download it.
One thing you can do is change the element name from img to something else before building the dom, or change the src attribute to something else, for example:
// change the <img> elements to <my_img> to avoid image fetching
strHtml = strHtml.replace(/<img /gi, "<my_img ").replace(/<\/img>/gi, "</my_img>");
// or the 2nd alternative: change the src attribute of images
strHtml = strHtml.replace(/<img([^>]*?) src=/gi, "<img$1 my_src=")
// now its safe to parse into DOM - no images will be fetched
var dom = $(strHtml);
note this simple "search and replace" may replace texts other than the elements you want, but it may be sufficient for your use case.
You can feed it through $.parseXML first:
var strHTML = "<div><img src='/fake/path/fakeImage.jpg'/><span id='target'>text to extract</span></div>";
var dom = $($.parseXML(strHTML));
var extractedText = dom.find("#target").text();
alert(extractedText);

Replaced string shows the tag in window

I replaced a part of a div (that is content editable) with a tagged word. Instead of showing just the content of that new word, it shows the tags as well.
Here's the original content of the div:
This is inside the <div> tag, and I'd like to replace this [[var12]]
This is how I'd like it to look:
This is inside the <div> tag, and I'd like to replace this var12
However, it ends up looking like this:
This is inside the <div> tag, and I'd like to replace this <span>var12</span>
This is the code that I used:
var pattern = new RegExp("\\[\\[var[0-9]*\\]\\]")
if ($(this).text().match(pattern)) {
var match = $(this).text().match(pattern);
var num = match.toString().match(/[0-9]+/);
var tagged = '<span class="variable">VAR ' + num + '</span>';
$(this).text($(this).text().replace(pattern, tagged));
}
It looks like that because you've specifically told it to escape the html by using .text(). If you want to insert html, you can use .html().
$(this).html($(this).text().replace(pattern, tagged));
From the .text() docs:
We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), does not interpret the string as HTML.

Injecting and executing JavaScript string in a specific HTML element

I have received the latest Disqus comments string (JavaScript code) from the server using ajax call that has document.write code in it.
I want the page to execute this code inside a specific DIV (by it Id, which is '#recent-comments') in the page, how do I do that?
I use jQuery 2.1.1.
Its a bit nasty but you could eval it inside a closure function:
var message =" document.write('hello'); ";
eval("(function(){"+
"var document = {write:function(text){$('#divName').html(text)}}; " +
message +
" })();");
JSFiddle DEMO (I've had to change write to wrie otherwise jsfiddle disallows it, just need to change back for your case)
Since it is coming as a string, you need to create a script element and put the string (inside document.write) as a element to the div.
var sampleStr = "document.write(\"Hello World\");";
var str, scriptElement = document.createElement('script');
str = sampleStr.replace(/["']/g, '"');
str = str.replace(/"document.write/g, "");
scriptElement.innerHTML = str;
$('#div1').append(scriptElement);
Updated Fiddle

How to replace text between two XML tags using jQuery or JavaScript?

I have a XML mark-up/code like the following. I want to replace the text inside one of the tags (in this case <begin>...</begin>) using JavaScript or jQuery.
<part>
<begin>A new beginning</begin>
<framework>Stuff here...</framework>
</part>
The source is inside a textarea. I have the following code, but it is obviously not doing what I want.
code=$("xml-code").val(); // content of XML source
newBegin = "The same old beginning"; // new text inside <begin> tags
newBegin = "<begin>"+newBegin +"</begin>";
code=code.replace("<begin>",newBegin); // replace content
This is just appending to the existing text inside the begin tags. I have a feeling this can be done only using Regex, but unfortunately I have no idea how to do it.
You can use the parseXML() jQuery function, then just replace the appropriate node with .find()/.text()
var s = "<part><begin>A new beginning</begin><framework>Stuff here...</framework></part>";
var xmlDoc = $($.parseXML(s));
xmlDoc.find('begin').text('New beginning');
alert(xmlDoc.text());
http://jsfiddle.net/x3aJc/
Similar to the other answer, using the $.parseXML() function, you could do this:
var xml = $.parseXML($("xml-code").val());
xml.find('begin').text('The same old beginning');
Note that there is no need to replace a whole node, just change it's text. Also, this works if there are multiple <begin> nodes that need the text as well.
You can user regular expression but better dont do it. Use DOM parsers.
var code = $('xml-code').html(); // content of XML source
var newBegin = "The same old beginning"; // new text inside <begin> tags
var regexp = new Regexp('(<part>)[^~]*(<\/part>)', i);
code = code.replace(regexp, '$1' + newBegin + '$2');

Is there a way to convert HTML into normal text without actually write it to a selector with Jquery?

I understand so far that in Jquery, with html() function, we can convert HTML into text, for example,
$("#myDiv").html(result);
converts "result" (which is the html code) into normal text and display it in myDiv.
Now, my question is, is there a way I can simply convert the html and put it into a variable?
for example:
var temp;
temp = html(result);
something like this, of course this does not work, but how can I put the converted into a variable without write it to the screen? Since I'm checking the converted in a loop, thought it's quite and waste of resource if keep writing it to the screen for every single loop.
Edit:
Sorry for the confusion, for example, if result is " <p>abc</p> " then $(#mydiv).html(result) makes mydiv display "abc", which "converts" html into normal text by removing the <p> tags. So how can I put "abc" into a variable without doing something like var temp=$(#mydiv).text()?
Here is no-jQuery solution:
function htmlToText(html) {
var temp = document.createElement('div');
temp.innerHTML = html;
return temp.textContent; // Or return temp.innerText if you need to return only visible text. It's slower.
}
Works great in IE ≥9.
No, the html method doesn't turn HTML code into text, it turns HTML code into DOM elements. The browser will parse the HTML code and create elements from it.
You don't have to put the HTML code into the page to have it parsed into elements, you can do that in an independent element:
var d = $('<div>').html(result);
Now you have a jQuery object that contains a div element that has the elements from the parsed HTML code as children. Or:
var d = $(result);
Now you have a jQuery object that contains the elements from the parsed HTML code.
You could simply strip all HTML tags:
var text = html.replace(/(<([^>]+)>)/g, "");
Why not use .text()
$("#myDiv").html($(result).text());
you can try:
var tmp = $("<div>").attr("style","display:none");
var html_text = tmp.html(result).text();
tmp.remove();
But the way with modifying string with regular expression is simpler, because it doesn't use DOM traversal.
You may replace html to text string with regexp like in answer of user Crozin.
P.S.
Also you may like the way when <br> is replacing with newline-symbols:
var text = html.replace(/<\s*br[^>]?>/,'\n')
.replace(/(<([^>]+)>)/g, "");
var temp = $(your_selector).html();
the variable temp is a string containing the HTML
$("#myDiv").html(result); is not formatting text into html code. You can use .html() to do a couple of things.
if you say $("#myDiv").html(); where you are not passing in parameters to the `html()' function then you are "GETTING" the html that is currently in that div element.
so you could say,
var whatsInThisDiv = $("#myDiv").html();
console.log(whatsInThisDiv); //will print whatever is nested inside of <div id="myDiv"></div>
if you pass in a parameter with your .html() call you will be setting the html to what is stored inside the variable or string you pass. For instance
var htmlToReplaceCurrent = '<div id="childOfmyDiv">Hi! Im a child.</div>';
$("#myDiv").html(htmlToReplaceCurrent);
That will leave your dom looking like this...
<div id="myDiv">
<div id="childOfmyDiv">Hi! Im a child.</div>
</div>
Easiest, safe solution - use Dom Parser
For more advanced usage - I suggest you try Dompurify
It's cross-browser (and supports Node js). only 19kb gziped
Here is a fiddle I've created that converts HTML to text
const dirty = "Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>";
const config = { ALLOWED_TAGS: [''], KEEP_CONTENT: true, USE_PROFILES: { html: true } };
// Clean HTML string and write into the div
const clean = DOMPurify.sanitize(dirty, config);
document.getElementById('sanitized').innerText = clean;
Input: Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>
Output: Hello world Many other tags are stripped
Using the dom has several disadvantages. The one not mentioned in the other answers: Media will be loaded, causing network traffic.
I recommend using a regular expression to remove the tags after replacing certain tags like br, p, ol, ul, and headers into \n newlines.

Categories