Javascript or jQuery for Adding Style to Phrases on Page - javascript

I'm applying a style to a certain phrase on our website over and over again. Is there a way to search the page for instances of that phrase and apply that style automatically?
Example:
<div>
This is what you get from <span class="comp">Company Name</span>.
We do all kinds of things here at <span class="comp">Company Name</span>.
</div>

You could take a look at these questions:
Highlight a word with jQuery
How to highlight certain words with jQuery
Both of the top answers point to the highlight plugin for jQuery.

sure...
http://docs.jquery.com/Selectors/contains#text
$("div:contains('Conpany Name')").css("text-decoration", "underline");

var body = document.getElementByTagName("body")[0].innerHTML;
body.replace(/Company Name/g, '<span class="comp">Company Name</span>');
document.getElementByTagName("body")[0].innerHTML = body;
The above should get everything in the body and replace it with your span and that doesnt need jQuery.

Related

How to find position of a word in a div (y coordinate)

I have a lot of text within a DIV. I would like to be able to search it on a string using perhaps a PHP regex then find the y position of that text that is searched on so I can place an image next to it.
I believe this would be the best way of doing it, I am unsure. However, I can't figure out how to determine how many pixels from the top of the screen that line is. Any recommendations?
#user1524441 not sure if this what you mean but from what I understand you want to add an image next to a specific search term, if this is the case you can use the following approach assuming you are using jquery:
var search = "Robin";
var text = $('.content').text();
$('.content').html(text.replace(search,'<span class="search-term" style="font-weight:bold;">' + search + '</span>'));
$('.search-term').before('<img src="url/goes/here" alt="" title=""/>');
here is a jsfiddle displaying how it works http://jsfiddle.net/6YsfB/
you can use substring and indexOf
var serch = "Robin"
var text = "hi my name is Robin, what you so talk? I'm god";
document.write(text.substring(text.indexOf(serch),text.indexOf(serch)+(serch).length));
http://jsfiddle.net/5bejQ/1/
If you're doing the search on the server, you could output the found text wrapped in <span> tags with a certain CSS class:
Here is some text with the <span class = "highlighted">text of interest</span> highlighted.
Then you could use the CSS "content" property (http://css-tricks.com/css-content/) in conjunction with the :before or :after pseudo-classes to show an image before or after the highlighted text.

HTML DOM manipulation : properly replace tag by heading tag

I want to replace some tag-inside-a-paragraph-tag by a heading-tag-enclosed-by-a-paragraph tag. This would result in proper W3C coding, but it seems that jQuery is not able to manipulate the DOM in the right way!? I tried several ways of (jQuery) coding, but i can't get it to work ..
Original code:
<p>some text <span>replace me</span> some more text</p>
Desired code:
<p>some text</p><h2>my heading</h2><p>some more text</p>
Resulting code by jQuery replaceWith():
<p>some text<p></p><h2>my heading</h2><p></p>some more text</p>
Demo: http://jsfiddle.net/foleox/J43rN/4/
In this demo, look at "make H2 custom" : i expect this to work (it's a logical replace statement), but it results in adding two empty p-tags .. The other 2 functions ("make code" and "make H2 pure") are for reference.
Officially the W3C definition states that any heading tag should not be inside a paragraph tag - you can check this by doing a W3C validation. So, why does jQuery add empty paragraph tags? Does anybody know a way to achieve this? Am i mistaken somehow?
You can achieve this with this code. However it's pretty ugly:
$('.replaceMe').each(function() {
var $parent = $(this).parent(),
$h2 = $(this).before('$sep$').wrap('<h2>').parent().insertAfter($parent);
var split = $parent.html().split('$sep$');
$parent.before('<p>' + split[0] + '</p>');
$h2.after('<p>' + split[1] + '</p>');
$parent.remove();
});
http://jsfiddle.net/J43rN/5/
If you read the jQuery docs, you will find:
When the parameter has a single tag (with optional closing tag or
quick-closing) — $("<img />") or $("<img>"), $("<a></a>") or $("<a>")
— jQuery creates the element using the native JavaScript
createElement() function.
So that is exactly what it is doing. And as I said in my comment, you can't change a parent node from a child node, you're altering the DOM here, not HTML code. So you'll need to either use replaceWith on the parent node and replace everything or use something like remove and append to split it up in multiple elements which you append after each other.
Try this:
var temp = "<p>some text <span>replace me</span> some more text</p>";
temp.replace(/(\<span\>replace me\<\/span\>)/gi, '</p><h2>my heading</h2><p>');
This will do a case insensitive replace for multiple occurences as well.
Read more about capturing groups here
Original credit to this question!
Please try this I have updated the http://jsfiddle.net/J43rN/6/ example by the below java script function please check I hope it will work for you
function fnMakeCode() {
$('#myP #replaceMe').html("<code id='replaceMe'>My Code</code>");
}
function fnMakeH2pure() {
$('#myP #replaceMe').html("<h2 id='replaceMe'>My H2 pure</h2>");
}
function fnMakeH2custom() {
$('#replaceMe').html("<p></p>").html("<h2>My H2 custom</h2>");
}

Wrap a new div element around specific text

I am struggling with this one.
How can I wrap a new <div> element around text that does not have any class or ID?
Below is the scenario:
<div class="ContentDiv">.....</div>
Share your knowledge. Be the first to write a review »
I need the new div to wrap around "Share your knowledge. Be the first to write a review »"
I have tried the following:
$(document).ready(function() {
$('.ContentDiv').each(function() {
$(this).add($(this).next()).wrapAll('<div class="NewDiv"></div>');
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ContentDiv">.....</div>
Share your knowledge. Be the first to write a review »
but it is not working because it wraps around the <a> element only and leaves the text below it. I need the rest of the text in there as well.
You need to get the next textnode after .ContentDiv and wrap that:
$('.ContentDiv').each(function() {
$(this).next('a').add(this.nextSibling).wrapAll('<div class="NewDiv"></div>');
});
FIDDLE
Since jQuery does'nt really get textnodes, the native nextSibling should work.
For this you can add a div after $('.ContentDiv') and then add the html to it.
$("<div id='new_div'></div").insertAfter($('.ContentDiv')).html("Share your knowledge. <a href='URL'>Be the first to write a review »</a>");

replace content of div with another content

I've been building a list of links, all of which should change the content of a div to another specific content (about 4 lines of stuff: name, website, contact etc.) upon a click.
I found this code:
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
and used it in such a way:
<li class="pl11">
superlink')">Pomorskie</a>
</li>
And it doesn't work as I expected.
It changes hyperlinks text from 'Pomorskie' to 'superlink'.
The plain text works just fine but I need links.
here's the http://xn--pytyfundamentowe-jyc.pl/projektanci/kontakty-p/ (only two of them show anything)
But after trying all of your recomendations, I think I'd jump to different divs with #links, cause nothing worked with this :/
Thanks a lot for trying, and cheers :)
Just as a completely sideways look at this, I'd suggest avoiding the nesting weirdness / complexity, and reducing the problem down.
Setup the content in a hidden (ie. <div id="replacements">...</div>) Grab the innerHTML from the node you want, and be done with it.
Much easier to get replacement content from non-devs that way too, kinda works great if you're in a team.
// Probably better in a separate helpers.js file.
function replaceContentInContainer(target, source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
Control it with: (lose that href=javascript: and use onClick, better as an event handler, but for brevity I'll inline it as an onClick attribute here, and use a button.)
<button onClick="replaceContentInContainer('target', 'replace_target')">Replace it</button>
We have our target somewhere in the document.
<div id="target">My content will be replaced</div>
Then the replacement content sits hidden inside a replacements div.
<div id="replacements" style="display:none">
<span id="replace_target">superlink</span>
</div>
Here it is in JSBin
Improve the dynamic nature of this by using Handlebars or another nice JS templating library, but that's an exercise for the OP.
edit: Note, you should also name functions with a leading lowercase letter, and reserve the leading uppercase style for Class names e.g. var mySweetInstance = new MySpecialObject();
The quotes are mismatched! So when you click you are getting a JavaScript error.
The browser sees this string:
href="javascript:ReplaceContentInContainer('wojewodztwo', 'superlink')">Pomorskie<
as:
href="javascript:ReplaceContentInContainer('wojewodztwo', '<a href="
Chnage the " inside to #quot;
<li class="pl11">
Pomorskie
</li>
Example fiddle.
Also note, using the href tag for JavaScript is a BAD practice.
You've got a problem with nested quotes. Take a look in your DOM inspector to see what the HTML parser built from it! (in this demo, for example)
You either need to HTML-escape the quotes inside the attribute as " or ", or convert them to apostrophes and escape them inside the JS string with backslashes:
<a href="j[…]r('wojewodztwo', '<a href="http://address.com">superlink</a>')">…
<a href="j[…]r('wojewodztwo', '<a href=\'http://address.com\'>superlink</a>')">…
See working demos here and here.
Better, you should use a onclick attribute instead of a javascript-pseudo-url:
<a onclick="ReplaceContentInContainer('wojewodztwo', …)">Pomorskie</a>
or even a javascript-registered event handler:
<li class="pl11">
<a id="superlink">Pomorskie</a>
</li>
<script type="text/javascript">
function replaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
document.getElementBId("superlink").onclick = function(event) {
replaceContentInContainer('wojewodztwo', 'superlink');
event.prevenDefault();
};
</script>
(demo)

Replace html placeholder text with html element using javascript

I have a scenario where i have in my page a placeholder text that I will replace after the page is fully loaded.
My problem is that the text i need to replace is a plugin of the recaptcha image, for example:
I have the text loading... which will be replaced by:
<recaptcha:recaptchacontrol ID='recaptcha' runat='server' PublicKey='kfldsjfh4378qyf43h4eidfhew' PrivateKey='sdflkdsfy908s6dfdsfkj' Theme='clean' />
I couldn't find a way to do so, any help will be appreciated.
found the answer in chat:
as the <recaptcha:...> tags are parsed by some server side plugin, they were not rendered after writing them in client side JS. so replacing works fine, but plugin didn't...
you can do any string operations (like search and replace) on document.body.innerHtml:
document.body.innerHtml = document.body.innerHtml.replace(/Loading\.\.\./g,
"<recaptcha...>");
Wrap your "Loading..." text in a <span> with a unique id, such as
<span id="removeme">Loading...</span>
Then, if you don't want to do much DOM-fu with that complex, namespaced tag, you can do the following:
var removeme = document.getElementById('removeme');
removeme.innerHTML = "<recaptcha:recaptchacontrol ...";
var recaptchaThing = removeme.firstChild;
removeme.removeChild(recaptchaThing);
var parent = removeme.parentNode;
parent.insertBefore(recaptchaThing, removeme);
parent.removeChild(removeme);
This will replace the <span> with the <recaptcha:recaptchacontrol> element, after letting the browser figure out how to build the DOM for that bizarre element. If it turns out <recaptcha:recaptchacontrol> can't be placed inside of a <span> element, make it a <div style="display:inline"> instead.

Categories