Currently with a site I'm working on, when you search in the global header you are taken to the search results page. Once you are on the search results page, you can see your search in the url. Example: I searched elephant, search-results.html?elephant. I need my search results page to highlight everything on the page that matches the value, and only the value. I don't want the highlight to pick up "search" or "results just after the question mark, the value. The closest solution I've found is this
http://www.nsftools.com/misc/SearchAndHighlight.htm
but it somehow interrupts my css div headers. Also, (and maybe my brain is just fried from staring at this code for too long) how can I customize this code to read my value? This seems like a solution as well, but I can't get it to work. I used the function highlightSelection() with a body onload and no luck.
http://www.switchonthecode.com/tutorials/javascript-highlighting-selected-text
or even the post here by Coopster, if I could capture the value from the url. I know I can document.write(window.location.search.substr(1)) and it will show me.
http://www.webmasterworld.com/forum83/2418.htm
Thanks for your help guys.
You can try to use the contains:
http://docs.jquery.com/Selectors/contains#text
$("span:contains('Hey')").css("text-decoration", "underline");
The issue with this you must have a class or something that you want to search specifically, you can do a *:contains but it will end up grabbing every element.
http://jsfiddle.net/dLdb2/
You will need ot grab the $_GET value through either javascript or whatever back end you are using. Here is a link to grab it with jQuery:
retrieving $_GET variable in jquery
You can use a part of the Chad solution to retrieve span that contain the specific text.
Then, instead of applying a CSS rule to the whole HTMLElement, you can retrieve its content with .html(), wrap the specific word with specific <span> and then update the content with .html() method again.
// Retrieve and explode URL
var urlParts = window.location.href.split("?");
if (urlParts.length == 2)
{
// Retrieve all span containing the word
$("span:contains('" + urlParts[1] + "')").each(function(index, spanElement) {
var jQSpan = $(spanElement);
jQSpan.html(jQSpan.html().replace(urlParts[1], '<span class="special">' + urlParts[1] + '</span>'));
});
}
Assuming you have a .special CSS class that will highlight the word.
.special {
background-color: yellow;
}
Note: The word in the Javascript function could be injected via PHP or other server side language.
Here is a complete example, assuming your URL is http://path/to/your/file.php?Lorem
<html>
<head>
<script type="text/javascript" src="path/to/your/jQuery.js"></script>
</head>
<body>
<span>
Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression.
</span>
<script type="text/javascript">
// Start when DOM is ready
$(document).ready(function() {
var urlParts = window.location.href.split("?");
// Highlight word if we have a word in parameter
if (urlParts.length == 2)
{
// Retrieve all span containing the word
$("span:contains('" + urlParts[1] + "')").each(function(index, spanElement) {
var jQSpan = $(spanElement);
jQSpan.html(jQSpan.html().replace(urlParts[1], '<span class="special">' + urlParts[1] + '</span>'));
});
}
});
</script>
</body>
</html>
Explanation: When the DOM is ready, the Javascript code will try to extract the part of the URL after the '?' (in our case, this is 'Lorem'). Then, Javascript retrieve, via jQuery, all span containing this word and loop on each span to wrap the word with special span (span with CSS class 'special')
If you change the word in the URL and reload the page, the highlight will change dynamically
Related
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);
I'm wondering if its possible to write in a document with Javascript by using the script tags as a reference, instead of some section found with document.getElementById("id") or something like that.
Example: I have a form where, when you put values in the inputs and press enter, it writes text to the document that uses the previously entered values.
Now, I know it would obviously be easier to go ahead and send it to a function with onSubmit in the head, but with the way this is set up it formats easier if I can write it out in this way. So, if anyone know how this could be achieved, tell me please, thanks.
<div style="text-align: center; font-size: 15pt; padding-top: 70px;">
<form onSubmit="reveal(this.a.value, this.b.value)">
a = <input name="a"/>
b = <input name="b"/>
</form>
<hr>
<script>
function reveal(a, b)
{
[math]a + b = c[math]
}
</script>
</div>
You can see what I have so far here on it. If anyone can tell me how to write the [math]a + b = c[math] to the document using the script tags as reference.
Clarification Of Attempted Result: [math]a + b = c[math] represents the text that I want to place in the document, as of now I don't have anything set up to actually write it, which is why its just sitting there. I want it to be placed in the document at the location of the script tags, the ones surrounding the function reveal(). How can I place that text in the document at the location of the surrounding script tags?
I believe this is what you are trying to do: find the script tag that has the function reveal(), then insert the string before or after the script tag.
If it is the case, then try this: (jQuery is used for the sake of simplicity)
var tag = $("script").filter(function () {
return /reveal\(\)/.test(this.innerText); //Find the script tag that has
}); // the function "reveal()"
tag.after("[math]a + b = c[math]"); //Insert your text
- or -
$("<span>[math]a + b = c[math]</span>").replaceAll(tag); //Replace it
Demo
PS:
If you already have a script tag, then why don't you just do this:
<script>
function reveal(){
blah();
}
document.write("[math]a + b = c[math]"); //The text will be inserted where
//the script tag is located at
</script>
I'm trying to teach myself jQuery and I'm a little stomped with the load() method. I'm working on eBay listings. Yes, I know includes are not allowed on ebay. However, there is a workaround that has been around for a few years and ebay doesn't seem to be cracking down on it.
var ebayItemID='xxxxxxxxxxxxxx'; // This is eBay code. I cannot edit it.
<h1 id="title"> TO BE REPLACED</h1>
$(document).ready(function(){
var link = "http://www.ebay.com/itm/" + ebayItemID + "?item=" + ebayItemID + &viewitem=&vxp=mtr";
var newTitle = $('#title').load(link + "#itemTitle");
$('#title').html(newTitle);
});
What's the point of this. I want to show the item title on the description, but I want to do so dynamically,
load will not work on different domains (ebay on your case)
load will set the content directly to your element. You can't assign it to a var.
If you would like to indicate you want to extract content from a specific element you need to add a space between your link and the element id:
You can find more info on the jQuery docs
$('#title').load(link + ' #itemTitle', function() {
alert('Load was performed.');
});
When you use load will place the returned html into the element(this case #title).
So you don't need to call html after it.
Hi here is my total work to search a string in HTML and highlight it if it is found in document:
The problem is here
var SearchItems = text.split(/\r\n|\r|\n/);
var replaced = body.html();
for(var i=0;i<SearchItems.length;i++)
{
var tempRep= '<span class="highlight" style="background-color: yellow">';
tempRep = tempRep + SearchItems[i];
tempRep = tempRep + '</span>';
replaced = replaced.replace(SearchItems[i],tempRep); // It is trying to match along with html tags...
// As the <b> tags will not be there in search text, it is not matching...
}
$("body").html(replaced);
The HTML I'm using is as follows;
<div>
The clipboardData object is reserved for editing actions performed through the Edit menu, shortcut menus, and shortcut keys. It transfers information using the system clipboard, and retains it until data from the next editing operation replace s it. This form of data transfer is particularly suited to multiple pastes of the same data.
<br><br>
This object is available in script as of <b>Microsoft Internet Explorer 5.</b>
</div>
<div class='b'></div>
If I search for a page which is pure or without any html tags it will match. However, if I have any tags in HTML this will not work.. Because I am taking body html() text as the target text. It is exactly trying to match along with html tags..
In fiddle second paragraph will not match.
First of all, to ignore the HTML tags of the element to look within, use the .text() method.
Secondly, in your fiddle, it wasn't working because you weren't calling the SearchQueue function on load.
Try this amended fiddle
Alrite, I have seen other Questions with similar titles but they don't do exactly what Im asking.
I have 2 x HTML documents, one containing my page, one containing a element with a paragraph of text in it. As-well as a separate .js file
what I want to do is extract this text, store it as a JS variable and then use jQuery to edit the contents of an element within the main page. This is the conclusion I came to but it didnt work as expected, im not sure if it is me making a syntax error or if i am using the wrong code completely:
$(document).ready(function(){
var c1=(#homec.substring(0))
// #homec is the container of the text i need
$(".nav_btn #1").click(function(c1){
$(".pcontent span p") .html(+c1)}
);
});
i know +c1 is most probably wrong, but i have been struggling to find the syntax on this one. thankyou in advance :D
var c1=(#homec.substring(0)) will throw an error because #homec is not a valid variable name, is undefined, and does not have a property function called substring. To get the html of an element with an id of homec, use the html method:
var c1 = $("#homec").html();
c1 should not be an argument of the click function because it is defined in the parent scope. +c1 is unnecessary because you do not need to coerce c1 to a number.
If you are trying to add content to the end of the paragraph, use the append method:
$(".pcontent span p").append(c1)
That means you should use this code instead:
$(document).ready(function() {
var c1 = $("#homec").html();
$(".nav_btn #1").click(function() {
$(".pcontent span p").append(c1)
});
});
P.S. Numbers are not valid ID attributes in HTML. Browsers support it, so it won't make anything go awry, but your pages won't validate.
Try this:
$(".nav_btn #1").click(function(c1){
var para = $(".pcontent span p");
para.html(para.html() + c1);
});
The JQuery text() function will allow you to get the combined text contents of each element in the set of matched elements, including their descendants. You can then use the text(value) function to set the text content of your target paragraph element. Something like this should suffice:
$(document).ready(function() {
var c1 = $("homec").text();
$(".nav_btn #1").click(function() {
$(".pcontent span p").text(c1);
});
});
See the JQuery documentation for more details on the text() function. If you need to capture the full structure of the other document, then try the html() function instead.