how can i convert this jquery code to vanilla Javascript
$("h2:contains('" + search + "')").closest(".element").show();
$("h2:not(:contains('" + search + "'))").closest(".element").hide();
i got the second half of the line to be
closest(".element").style.display = "block"
but i cant find a way for the first half to work in normal Javascript. I am creating a live search function to match the text in the search input to match the h2. if they match it will display the content if not the content will display as none.
In Jquery contains gives you a string of text to look for.
So here you need to get all the h2 tag and search in their text.
As h2 elements don't have a value, you should use innerHTML and then instead of contains, you should use includes method.
var allHTwos= document.getElementsByTagName('h2');
for (i=0; i<allHTwos.length; i++) {
var gh = allHTwos[i];
var ts = gh.innerHTML;
if(ts.includes(search)){
// Do your hide/unhide here
}
}
Related
Both the $("<test") & document.createElement(",test") throws error due to < character associated to the text. I do not want to replace the character & wanted to see if there is option to create dom or jquery object using such text. I know replace will work but since the code is pre-existing & also since code is written such that it assume it can either have the simple text (textnode) or html tag (like span) hence this error is occuring as it fails to check if it is proper self closing html tag.
I am thinking of creating it to xml node & then check if the childnode is textNode or not before trying to create jquery object,however I am looking for suggestion & best approach to tackle such issue. I know replace of < will work & also there is no need to check for attributes of plain text but since the code is dynamic it sometimes retrieves plain text & some time it gives valid html tag that why this issue appears
I am not sure what your exact end goal is, but basically you need to do something like this:
function makeElemHack( str ) {
var div = $("<div>").html(str); //create a div and add the html
var html = div.html(); //read the html
if (!html.length) { //if the html has no length the str was invalid
div.html(str.replace(/</g,"<")); //escape the < like text should be
//div.text(str); //or you can just add it as plain text
}
return div; //with the div wraper
//return div.contents(); //without the div wrapper
}
var bd = $("body");
bd.append( makeElemHack("<p>Hello</p>") );
bd.append( makeElemHack("1<0") );
bd.append( makeElemHack("<booo") );
Hi I need to edit some links on a page. Using the below code works but causes other problems on the page. I need the code to only affect elements with a certain input id. I also can't just replace the links as a query will be dynamically added to the end of each link. So in summary i just need to replace parts of all links with an input id "btnViewDetails". Any help would be great I'm very stuck. Cheers
<script language="javascript">
document.body.innerHTML = document.body.innerHTML.replace(/JobSeekers/g,'mobile');
document.body.innerHTML = document.body.innerHTML.replace(/JobPositionDetail.aspx/g,'JobPositionDetail_Mobile.aspx');
</script>
var someVariable = document.getElementsByClassName('btnViewDetails');
(you should use class instead of ID, if it is not a unique value).
someVariable is now an array holding all elements with class name btnViewDetails.
Now replace the text you want to replace only on the href values of you elements (you will have to loop over them):
for (i = 0; i < someVariable.length; i++) {
someVariable[i].href // do your replaces here
}
When a user create a message there is a multibox and this multibox is connected to a design panel which lets users change fonts, color, size etc.. When the message is submited the message will be displayed with html tags if the user have changed color, size etc on the font.
Note: I need the design panel, I know its possible to remove it but this is not the case :)
It's a Sharepoint standard, The only solution I have is to use javascript to strip these tags when it displayed. The user should only be able to insert links, images and add linebreaks.
Which means that all html tags should be stripped except <a></a>, <img> and <br> tags.
Its also important that the attributes inside the the <img> tag that wont be removed. It could be isplayed like this:
<img src="/image/Penguins.jpg" alt="Penguins.jpg" style="margin:5px;width:331px;">
How can I accomplish this with javascript?
I used to use this following codebehind C# code which worked perfectly but it would strip all html tags except <br> tag only.
public string Strip(string text)
{
return Regex.Replace(text, #"<(?!br[\x20/>])[^<>]+>", string.Empty);
}
Any kind of help is appreciated alot
Does this do what you want? http://jsfiddle.net/smerny/r7vhd/
$("body").find("*").not("a,img,br").each(function() {
$(this).replaceWith(this.innerHTML);
});
Basically select everything except a, img, br and replace them with their content.
Smerny's answer is working well except that the HTML structure is like:
var s = '<div><div>Link<span> Span</span><li></li></div></div>';
var $s = $(s);
$s.find("*").not("a,img,br").each(function() {
$(this).replaceWith(this.innerHTML);
});
console.log($s.html());
The live code is here: http://jsfiddle.net/btvuut55/1/
This happens when there are more than two wrapper outside (two divs in the example above).
Because jQuery reaches the most outside div first, and its innerHTML, which contains span has been retained.
This answer $('#container').find('*:not(br,a,img)').contents().unwrap() fails to deal with tags with empty content.
A working solution is simple: loop from the most inner element towards outside:
var $elements = $s.find("*").not("a,img,br");
for (var i = $elements.length - 1; i >= 0; i--) {
var e = $elements[i];
$(e).replaceWith(e.innerHTML);
}
The working copy is: http://jsfiddle.net/btvuut55/3/
with jQuery you can find all the elements you don't want - then use unwrap to strip the tags
$('#container').find('*:not(br,a,img)').contents().unwrap()
FIDDLE
I think it would be better to extract to good tags. It is easy to match a few tags than to remove the rest of the element and all html possibilities. Try something like this, I tested it and it works fine:
// the following regex matches the good tags with attrinutes an inner content
var ptt = new RegExp("<(?:img|a|br){1}.*/?>(?:(?:.|\n)*</(?:img|a|br){1}>)?", "g");
var input = "<this string would contain the html input to clean>";
var result = "";
var match = ptt.exec(input);
while (match) {
result += match;
match = ptt.exec(input);
}
// result will contain the clean HTML with only the good tags
console.log(result);
Is there a way to hide all hashtags on the page with javascript?
For instance, I have a tag cloud underneath each post on a website I'm making. Each tag looks something like: #myhashtag
I want javascript (possibly css?) to run through the document and hide the "#" so that the tag ends up simply looking like: myhashtag
is this possible?
Let the hash tags be elements with a specific class. (Just edit the CSS selector accordingly if you have other identification marks.) Than 8 lines jQuery should do the trick:
$('.my-hash-tag').each(function(i, elem) {
var $elem = $(elem), text = $elem.text();
if(text.length > 0 && text.charAt(0) == '#') {
$elem.text(text.substring(1));
}
});
This will do the job, comments explain how it works. Currently it assumes the tags are inside anchors and inside a div with id #cloud however this is easily edited, just use a different element selector the concept remains the same.
var tagCloud = document.getElementById("cloud"); // Get tag cloud element
var tags = tagCloud.getElementsByTagName('a'); // Find all anchors within cloud (If they aren't anchors change this to containing elements or replace with a class search .etc
for (var i=0, max=tags.length; i < max; i++) { // Loop through tags
tags[i].innerHTML = tags[i].innerHTML.replace("#", ""); // Remove #'s
}
Working fiddle: http://jsfiddle.net/3ayhA/1/
var doc = document.body;
doc.innerHTML = doc.innerHTML.replace(/(\B)#(\w+)\b/g, '$2');
i am writing some code which need to access a div which contains the particular text
following is the small portion of code i am working on:
var txtElem = txtdiv.getElementsByTagName("div");
txtElem[9].style.border = "2px solid blue";
as seen above i am accessing particular div with the index number, but now i want to add more code which can return me index of div from txtElem which contains the selected text from page
You need to loop trough the divs and check the contents with innerHTML
Try the code below
var txtElem = txtdiv.getElementsByTagName("div");
for ( var i = 0; i < txtElem.length; i++) {
if(txtElem[i].innerHTML === "The text in the div") {
//i is the index of the div that contains the text you searched on
alert(i);
}
}
Loop through divs and use JQuery .html() to check the html content of the div element.
For ease of use you may want to use jquery see http://api.jquery.com/contains-selector/