How to remove element from HTML string? - javascript

This doesn't seem to be working, I get an Uncaught Type error on the .remove() line:
JS:
var str = $("a").html();
var $html = $.parseHTML(str);
$("i",$html).remove();
$("div").html($html);
HTML:
Hello <i>Bob</i>
<div></div>
How to get this to work?

You can remove the HTML tags by just using the .text() function.
var str = $("a").text();
$("a").text(str);
Which will result in:
Hello Bob
Example: http://jsfiddle.net/3s1c55w2/
How it works:
The $("a").text(); will retrieve only the text of the element, so in your case it will return Hello Bob.
Once you retrieve Hello Bob, simply set the a tags text value using .text(str) again, where the str is the value with no html tags.

You can clone a, change html code of clone and put clone inside div.
Fiddle.
$(document).ready(function()
{
var clone = $("a").clone();
clone.find("i").remove();
$("div").html(clone);
});

Maybe he's trying to remove i tags from every anchor.
http://jsfiddle.net/1fytum86/
$("a").each(function(index) {
var str = $(this).text();
$(this).html(str);
});
Anyway, it's possible that he was getting a type error because parseHTML() parses a string into an array of DOM nodes. Best of luck!

If you are trying to remove the italics and leave the text:
$("a").html($("a").html().replace(/<\/?i>/g, ""));
Otherwise, the other answers using either remove or detach would be appropriate.

Related

How to get element(tag) inner text in pure js

I have a string named stringElement and its value is anchor tag but in string not as node element.
How to get the inner text of that tag in pure js?
How it was done using jQuery:
var stringElement = "<a>1</a>";
nodeElement div = document.createElement('div');
$(div).append(stringElement);
var nodeElement2 = $(div).find("a")[0];
var text = $(nodeElement2).text();
text value is 1 <=== This is the target
EDIT: My bad, I found the answer in another question and this should be marked as duplicate.
Here is the questions link:
Converting HTML string into DOM elements?
Here is the answer link that worked for me:
https://stackoverflow.com/a/3104237/2648837
try this,usetextContent or innerText
var str = "<a>1</a>";
var div=document.createElement('div');
div.innerHTML=str;
console.log(div.children[0].textContent);
console.log(div.children[0].innerText);

Detect html tag on a string, get the value and remove values inside html tag in javascript

I have a String which contains HTML tags:
var str = "Hello World <br><p>1</p><em>My First Javascript</em>";
And i also have a form with hidden input:
<input type='hidden' name='id' value=''>
With that String above, i want to get the value inside <p> tag which is 1 and assign that value to hidden input. And after that, i wanted to remove all the HTML tag inside the string which are these <br><p>1</p><em>My First Javascript</em>. So therefore the only value of str will be Hello World.
Is there any way how to do this on Javascript or jquery?
Thanks guys!
So, what you want to be doing is to convert your string into a jQuery object. You can do so like this -
var str = "Hello World <br><p>1</p><em>My First Javascript</em>";
var $holder = $('<div>');
$holder.append(str);
Now we have your string encapsulated within another div element. Next we extract the value within the <p> element -
var value = $holder.find('p').text(); // 1
Now that we have that value we can place it into the hidden input field -
$('input[name="id"]').val(value);
Now to remove all other elements from the original string - we'll use the container we created earlier for this -
$.each($holder.children(),function(index,elem){
$(elem).remove();
});
Now we can take the textual contents of $holder with $holder.text() and it should be just -
Hello World
If you would like to fiddle with this,
you can do so here - http://jsfiddle.net/TVXbw/1/
Ok, a quick and simple way:
var tmpDiv = document.createElement('div');
tmpDiv.innerHTML = str;//where str is the html string, obviously...
var pTagValue = tmpDiv.getElementsByTagName('p')[0].innerHTML;//=== '1'
document.getElementById('yourInputId').value = pTagValue;
If I understood correctly, that's what you're after, right?

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.

String replacing in a div

I want to replace a particular string in #TextArea1. This happens when a button is clicked.
Trying it out with the below code, but unable to get it work:
$('#TextArea1').text().replace("wef","--");
What is the correct syntax to replace a word in a div?
Pass a function to the text()[docs] method that returns the value you want set:
$('#TextArea1').text(function( i, txt ) {
return txt.replace("wef","--");
});
The function parameters are as follows:
i is the index of the current element in the iteration
txt is the current text content of the current element
The value returned from the function will be set as the new value for the current element.
You are close, try this:
$('#TextArea1').text($('#TextArea1').text().replace(/wef/g,"--"));
Or an optimized one
var $textarea = $('#TextArea1');
$textarea.text($textarea.text().replace(/wef/g,"--"));
If it's a textarea element, you would do:
var $textarea = $('#TextArea1');
$textarea.val($textarea.val().replace(/wef/g,"--"));
You have set the text also:
var text = $('#TextArea1').text().replace("wef","--");
$('#TextArea1').text(text);
or, using a function:
$('#TextArea1').text(function(index, text) {
return text.replace("wef","--");
});
Note: if this is a <textarea>, use val() instead of text().
var text = $('#TextArea1').val().replace("wef","--");
$('#TextArea1').val(text);
replace() creates a new string and returns it, so it's getting returned into thin air. You need to grab the new string and send it back into the textbox. This jsfiddle shows how.
<textarea id="t">
hello
</textarea>
var text = $('#t').text();
text = text.replace('h', 'b');
$('#t').text(text);

Trying to .replace() Without Success

I have some lines of HTML code that are like this:
<li>Testing jQuery [First Bracket]</li>
<li>Loving jQuery [Second one]</li>
I'm trying to replace what's inside the bracket with nothing onLoad, like this:
var item = $(".lstItem").text();
var match = item.match(/\[(.*?)\]/);
item = item.replace(match[0], "");
But nothing changes. What's wrong and how to correct this?
After using jimbojw's suggestion I'm getting a Uncaught ReferenceError: text is not defined at this particular line:
oldtext = $item.text,
item is a variable containing a string, not a pointer to the literal text. If you want to change the text, you have to set it again, vis a vis $(".listItem").text(item)
edit - predicting next problem
The next problem you're going to have is that all the text gets set to the same thing. So what you really want to do is probably something like this:
$(".lstItem")
.each(function(index, item) {
var
$item = $(item),
oldtext = $item.text(),
match = oldtext.match(/\[(.*?)\]/),
newtext = oldtext.replace(match[0], '');
$item.text(newtext);
});
this will do the job for you:
you are splitting your code in too much lines, also your need to run replace for each individual element separately.
$(".lstItem").each(function() {
$(this).html(
$(this).html().replace(/\[(.*)\]/, "")
);
});
see your example in jsFiddle: http://jsfiddle.net/eKn3Q/7/
Along with jimbojw's answer $(".lstItem").text() will retrieve all the text inside of your <a/> elements. One way to handle this would be to pass a function(i,t){} into the .text() method.
$(".lstItem").text(function(i, text){
var match = text.match(/\[(.*?)\]/);
return text.replace(match[0], "");
});
Simple example on jsfiddle
also your regex could be simpler.
var item = $(".lstItem").text();
var match = /\[(.*?)\]/;
$(".listItem").text(item.replace(match,""));

Categories