I want to strip all html tags from user input.
This code strip all html tags from #container, except anchor and img tags.
$("#container").find('*:not(a,img)').each(function() {
$(this).replaceWith(this.innerHTML);
});
I can't convert it to find input text .val();
$('#inputTxt').val().find('*:not(a,img)').each(function() {
$(this).replaceWith(this.innerHTML);
});
This code shows error :
$input.val().find() is not a function.
Can someone help me?
Updated POST
well, the example Mr antyrat gave was removing all contents inside any other tags, but I wanted content of them, just removing their tags. so I changed it like this and it's wokring.
var tmpElement = $( $( '#inputTxt' ).val() ); // create tmp HTML node
tmpElement.find('*:not(a,img)').each(function() {
$(this).replaceWith(this.innerHTML);
});
return tmpElement.html();
PROBLEM
above code works well with some inputs like these:
<div> Hello I am a link </div>
<a href="#" ></a><div>Hello<img src="url" /></div>
but when user types something like this:
<div><a <div ></div> href="#" ></a></div>
the output is : <a <div=""> href="#" >Another link</a>
This is the jsfiddle
This hapens because val() method returns input value, not the jQuery object, and this value doesn't have method find()
In your code:
$(this).replaceWith(this.innerHTML);
this is reference to jQuery element, not Node so you can't get innerHTML.
Also if inputTxt is input element you can't find any elements inside it as they are just plain text. You need to convert them to HTML at first, for example:
var tmpElement = $( $( '#inputTxt' ).val() ); // create tmp HTML node
tmpElement.find( '*:not(a,img)' ).remove(); // remove everything except <a> and <img> elements
$('#inputTxt').replaceWith( tmpElement ); // replace input to it's HTML content
But you need to be sure that input has correct HTML in it and has at least one root node. So better is to wrap your HTML into container, <div> for example:
var tmpElement = $( '<div>' + $( '#inputTxt' ).val() + '</div>' ); // create tmp HTML node
So the main problem you have is that you are trying to iterate over plain string like on elements.
See working demo on jsFiddle.
Update:
Event better is not to remove node w/ contents but just elements:
tmpElement.find( '*:not(a,img)' ).contents().unwrap(); // remove everything except <a> and <img> elements
updated jsFiddle
.val() returns a string, which is not a group of jquery objects, so .find() function doesn't work.
try:
$('#inputTxt').find('*:not(a,img)').each(function() {
$(this).replaceWith($(this).val());
});
Related
I have some HTML on a page that reads as follows:
<h3 class="ms-standardheader"><a name="SPBookmark_History"></a>History</h3>
I am running some javascript in the page READY where I am creating a dynamic hyperlink and I would like that to be inserted so that when the page renders the final result is:
<h3 class="ms-standardheader"><a name="SPBookmark_History"></a> History</h3>
The class name of the H3 exists on multiple page elements. The Name of the anchor tag, SPBookmark_History, is unique.
How can I accomplish this using JQuery or straight javascript?
Thank you
Just follow below code:
$(document).ready(function(){
var link = $('a[name=SPBookmark_History]');
link.attr('href','https://thissite.com/newurl');
link.attr('target','_blank');
});
JSFIDDLE SAMPLE
You can use:
Attribute Equals Selector [name=”value”]: in order to select the element because SPBookmark_History is unique
.closest( selector ): to get the parent h3 element.
.contents(): Get the children of each element in the set of matched elements, including text and comment nodes.
filter-function: in order to get only the text after the link
.wrap(): Wrap an HTML structure around each element in the set of matched elements.
The code:
$('a[name="SPBookmark_History"]').closest('h3.ms-standardheader')
.contents().
filter(function (idx, ele) {
return ele.nodeType == Node.TEXT_NODE
})
.wrap($('<a/>', {href: "https://thissite.com/newurl", target: "_blank"}));
console.log('Result is: ' + document.getElementsByClassName('ms-standardheader')[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="ms-standardheader"><a name="SPBookmark_History"></a>History</h3>
I am trying to delete a span class from a HTML string using Jquery. My HTML string looks like this:
<li class="left clearfix"><span id="userAvatar" class="chat-img pull-left"><img src="http://placehold.it/50/55C1E7/fff&text=U" alt="User Avatar" class="img-circle"></span><div class="chat-body clearfix"><div class="header"><strong class="primary-font">sdfsdf3424</strong></div><p>dfgfg</p></div></li>
To delete the span tag from this string I am doing the following:
var JqueryObj = $('<div/>').html(stringHTML).contents();
JqueryObj = JqueryObj.not("#userAvatar");
stringHTML = JqueryObj.html();
Where am I going wrong? Also is it possible to change the font color of the paragraph tag inside this string?
For your first question, you should just be able to do the following:
var htmlstring = '<li class="left clearfix"><span id="userAvatar" class="chat-img pull-left"><img src="http://placehold.it/50/55C1E7/fff&text=U" alt="User Avatar" class="img-circle"></span><div class="chat-body clearfix"><div class="header"><strong class="primary-font">sdfsdf3424</strong></div><p>dfgfg</p></div></li>'
var obj = $("div").html(htmlstring);
obj.find("#userAvatar").remove();
var newhtmlstring = obj.html();
This makes a new element that has the contents of the htmlstring in it. Then, the find part finds all direct and indirect children with the selector and removes them. finally, the new html string is the contents of the temporary object we created before.
Using .find(), you can also change the font color:
obj.find("p").css("color", "red");
here is a possible solution which explains how to remove span in a div.
var divContent = $("div").html(stringHTML);
divContent = $(divContent).find("#userAvatar").remove();
$("div").empty().html($(divContent).html());
use
$( "span" ).remove();
DEMO : http://jsfiddle.net/ryxbpn2s/2/
I am not exactly sure what you are trying to achieve so I will post a few solutions, maybe one of them will solve your problem.
1) You want to remove the a class from span#userAvatar:
You should use jQuerys removeClass function.
Usage:
$( "#userAvatar" ).removeClass( "className" )
2) You want to remove the span but keep the contents:
You can just replace the whole span with what's inside.
Usage:
$("#userAvatar").replaceWith(function() {
return $("img", this);
});
3) You want to remove the span class and everything that's inside it:
You should use jQuery's remove() function.
Usage:
$("#userAvatar").remove();
To change the colour of the paragraph you can use jQuery's find() function.
Usage:
JqueryObj.find("p").css("color", "#EEEEEE");
Hope this helps.
I would like to replace the innerHTML of a of a particular class with the innerHTML of a different elemets innerHTML based on that other elements class. I'm trying to dynamically match a header to the selected menu item.
Basically I want to take the innerHTML of whatever has the class "categorySidebarLabelSelected".
<a class="categorySidebarLabelSelected">Guest Relations</a>
And replace the "Start a document" with "Guest Relations" based on the class "areaTitle".
<div class="areaTitle">Start a document</div>
so the results would be:
<div class="areaTitle">Guest Relations</div>
Using getElementsByClassName.
document.getElementsByClassName('areaTitle')[0].innerHTML = document.getElementsByClassName('categorySidebarLabelSelected')[0].innerHTML;
Read something like that: http://api.jquery.com/text/
var str = $( "categorySidebarLabelSelected" ).text();
$( "areaTitle" ).html( str );
How can I create a HTML-Element dynamically, do something with it and then it should be removed.
But it is important that it will be really deleted.
Here is my approach:
var newdiv = document.createElement('div');
newdiv.setAttribute('id','MyDiv');
$('#MyDiv').css({'width':'100px','height':'100px'});
$('#MyDiv').html('This is a test');
$('#MyDiv').remove(); // It should be work ?
// Is it possible to delete it as follows?
newdiv.remove();
As I mentioned, it is important to really delete the element, since the Function "createElement()" can often get invoked.
How can I test whether the new created HTML-Element is really removed?
I test as follows, whether the element is still existed, but I get always true!
alert( $('#MyDiv').length == 1);
Below are a two links, but they were not enough for, in order to solve my problem.
setting the id attribute of an input element dynamically
createElement and delete DOMElement
Thanks.
try this one maybe is what you want:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var div = document.createElement("div");
$(function(){
$("body").append( div);
$(div).css({'width':'100px','height':'100px','border':'solid 1px black'}).html('This is a test');
//$(div).remove();
});
</script>
</head>
<body>
</body>
</html>
dont forget to uncoment the //$(div).remove();
First of all, I see, you have an error in your code in this line:
newdiv.setAttribute('id','#MyDiv')
value of id attribute must not have '#' (the hash sign) - with your code element newdiv will have id like "#MyDiv" but this is not valid ID for jQuery, due to jQuery use this template for ID Selector (“#idName”)
You can dynamically delete the element with your way, but I guess previously you should to append it to another element on page using jQuery.append(you element/selector) method
If you can use jQuery you can try with the following:
$( "body" ).append( "<div id="MyDiv">This is a test</div>" ); // Create MyDiv div before </body> tag (you can use .prepend( ... ) to create it after <body>)
$("#MyDiv").css({'width':'100px','height':'100px'}); // Give some style to MyDiv
$("#MyDiv").remove(); // Delete MyDiv
For example I have a list title like this: <li id="example"> title </li>. And here is where I want it to be "appended to" on a click of a button: <ol id="playlist"> </ol>
Here is the button: <span onClick="Button();"> Button </span>
Here is the function:
Button=function() {
$('#playlist').append('#example');
}
I just don't see why it doesn't work I mean when I make the .append('title') - so just plain text - it will add that text to the tag but when I try to append a whole tag through the ID it doesn't? It instead appends "#example" which isn't what I want. I'm sorry I am still trying to grasp this language however, I have honestly searched and scouted the whole internet to try find an anwser to this.
Try this:
$('#playlist').append($('#example'));
Fiddle
Update:
You can use the clone() method, try this:
$('#example').clone().attr('id', 'something').appendTo($('#playlist'))
Fiddle
You need to append the whole li, so your solution would be:
function Button() {
var $li = '<li id="example"> title </li>';
$('$playlist').append($li);
}
.append( content [, content] )
content: DOM element, HTML string, or jQuery object to insert at the
end of each element in the set of matched elements. ...
jQuery is assuming that you are appending the HTML string #example literally. Use one of the the other two options e.g.:
$('#playlist').append($('#example')); // append a jQuery object
For the sake of completeness:
$('#playlist').append(document.getElementById('example')); // append a DOM element