Target word using jQuery and add style - javascript

So, this could be a simple question, but my jQuery skills are just not quite up there (yet). I'm trying to target a specific word on a web page and add a style to it. The word I'm trying to target appears multiple times on the page. I googled around some and found this:
<script>
var divContent = document.getElementById("styled").innerHTML;
divContent = divContent.replace("Bevestigd","<span class='styled'>Bevestigd</span>");
divContent = divContent.replace("Geannuleerd","<span class='styled-r'>Geannuleerd</span>");
divContent = divContent.replace("Pending","<span class='styled-p'>Pending</span>");
document.getElementById("styled").innerHTML = divContent;
</script>
This works, kind of... It only targets the first time it encounters the word and doesn't repeat it self. I found numerous pieces of code to target a word on a page but this one seems to work the best... Is there any one that could help me out?
Is there a foreach function I'm missing?
I also tried this code:
$('body').html(
function(i,h){
return h.replace(/(Nike)/g,'<span class="nike tm">$1</span>');
});​
which seems a bit simpler but that didn't work... Maybe someone has a snippet for this or something?

This is your js code done on jquery. Check out this jsfiddle
$('#styled').html(function(i,v){
v=v.replace(/Bevestigd/g,'<span class="styled">Bevestigd</span>');
v=v.replace(/Geannuleerd/g,'<span class="styled-r">Geannuleerd</span>');
v=v.replace(/Pending/g,'<span class="styled-p">Pending</span>');
return v;
});
This is done with regex.
We can extend it further.
eg. To make the search case insensitive use /Bevestigd/gi instead of /Bevestigd/g.

Related

jquery's version of ".innerHTML +=" for an array html insertion

I have read through some questions pertaining specifically to innerHTML= vs .html(). But yet have crossed anything to add into the variable like innerHTML+= to the html(). Is there a jquery event that can add more than just one html string? Or shall I rely on innerHTML+= for now?
The coding that best describes the current issue:
var pushy = ['blah', 'blaH', 'blaah'];
for(i=0;i<pushy.length;i++){
document.getElementById("demo").innerHTML +=
"<div>Im one heck of a div and more!</div>" + pushy[i];}
vs
$("#demo").html("<div>Im one heck of a div and more!</div>" + pushy[i]);
//where it will return the last array value and not the first value
Although the first is the go to and failsafe. But wanted to see the exact equivalent than just pop the last value of the array. Here is my innerHTML+= vs .html() for example. The question is not pertaining to the innerHTML = but rather the += thereof.
You are probably looking for .append()
$('element').append('SOME HTML');
You example (updated)
https://jsfiddle.net/4pqegj5f/9/
are you looking for
$("#demo").append("<div>Im one heck of a div and more!</div>" + pushy[i]);
Using .append should get you the desired result. See below:
var pushy = ['blah', 'blaH', 'blaah'];
for(i=0;i<pushy.length;i++){
$("#demo").append("<div>Im one heck of a div and more!</div>" + pushy[i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="demo"></div>

htmlencode a string in javascript

Hello I have a function that loops around and then eventually a string gets sent to a DIV tag class...
$(document).ready(function addcopy() {
/* global */
$(".Bands").append('<div style="display: inline-block;">[EDIT] <h7 style="color:#7A0029;line-height: 110%;text-transform: uppercase;">[Custom:Name]</h7> </div>');
});
It works fine... however the token [Custom:Name] may contain special characters such as single or double quotes etc...
I've looked around these forums and tried to adapt my code to various solutions offered and it never seems to work, could somebody help me?
Thanks for your help!
Alex
EDIT(1):
Getting somewhere, from Ockert's and LeFex's answer I've adapted it below but it still does not work (replace speech marks and special characters from token which html can't handle)...
function htmlEncode(value){
return $('<div/>').text(value).html();
}
$(document).ready(function (){
/* global */
var band = $("<div style='display: inline-block;'>[EDIT] <a href='[LINK]'><h7 class='name' style='color:#7A0029;line-height: 110%;text-transform: uppercase;'>[Custom:Name]</h7></a> </div>");
band.appendTo(htmlEncode('.Bands'))
});
You can change your script too
$(document).ready(function (){
var band = $("<div style='display: inline-block;'>[EDIT] <a class='link' href='[LINK]'><h7 class='name' style='color:#7A0029;line-height: 110%;text-transform: uppercase;'>[Custom:Name]</h7></a> </div>");
band.find('.name').html("some weird name !##$%^&*");
band.find('.link').attr("href","http://www.google.com");
band.appendTo('.Bands');
});
By splitting it up like that, enables you to set the name to anything you want. You can easily select the name element
Have a look at this jsfiddle http://jsfiddle.net/fL3gn056/2/
You could use document.createElement instead of just appending a string.
http://www.w3schools.com/jsref/met_document_createelement.asp
If you just create your div, a and h7-elements, use the appendChild function, and add style and attributes and content by setting element properties, you should end up with a sollution that allows any special characters.
Edit:
I could'nt get it working using that method; however, with the approach I suggested above, i got some working code:
var element = document.createElement("div");
element.style.display = "inline-block";
var link = document.createElement("a");
link.setAttribute('href', "[LINK]");
var text = document.createElement("h7");
text.style.color = "#7A0029";
text.style.lineHeight = "110%";
text.style.textTransform = "uppercase";
text.innerHTML = "[CUSTOM:NAME]";
//not sure what you're appending it all to, but do it here
document.getElementsByClassName("Bands")[0].appendChild(element);
element.appendChild(link);
link.appendChild(text);
With this snippet, all input special characters are interpreted as a string, not as code. Some calls I could have put in the same line, but this way you get an easy to read overview.
Here's an earlier thread on the subject, and the top answer brings the issue of performance of different approaches to discussion.
jQuery document.createElement equivalent?

Regex works only once

I've recently been learning JavaScript by creating a little to do list web app here.
So far almost everything's working, but I have an issue if you try to check and uncheck an item more than once. If you keep checking/unchecking you'll see the delete button disappear and --> appear after the urgency icon.
The change of icon is done by a Regex changing code from commented to un-commented. I just don't understand why if it works once, it doesn't work every time?
if (tr.outerHTML.indexOf("checked=\"\"") >= 0) {
// replace checked with unchecked
var cookieHTML = tr.outerHTML.replace(/checked=\"\" class=\"list-checkbox\"/, 'class=\"list-checkbox\"')
.replace(/<tr class=\"list-row done\"/, '<tr class=\"list-row\"')
// change delete button to urgency.
.replace(/<!--<span aria-hidden=\"true\" data-icon=\"c\"/, '<span aria-hidden="true" data-icon="c"')
.replace(/alt=\"Neutral\"><\/span>-->/, 'alt="Neutral"></span>')
.replace(/<!--<span aria-hidden=\"true\" data-icon=\"f\"/, '<span aria-hidden="true" data-icon="f"')
.replace(/alt=\"Urgent\"><\/span>-->/, 'alt="Urgent"></span>')
.replace(/<span aria-hidden=\"true\" data-icon=\"e\"/, '<!--<span aria-hidden="true" data-icon="e"')
.replace(/onclick=\"deletetodo\(this\)\"><\/span>/, 'onclick="deletetodo(this)"></span>-->');
} else {
// else add checked to the input.
var cookieHTML = tr.outerHTML.replace(/class=\"list-checkbox\"/, 'checked class=\"list-checkbox\"')
.replace(/<tr class=\"list-row\"/, '<tr class=\"list-row done\"')
// change urgency to delete button.
.replace(/<span aria-hidden=\"true\" data-icon=\"c\"/, '<!--<span aria-hidden="true" data-icon="c"')
.replace(/alt=\"Neutral\"><\/span>/, 'alt="Neutral"></span>-->')
.replace(/<span aria-hidden=\"true\" data-icon=\"f\"/, '<!--<span aria-hidden="true" data-icon="f"')
.replace(/alt=\"Urgent\"><\/span>/, 'alt="Urgent"></span>-->')
.replace(/<!--<span aria-hidden='true' data-icon='e'/, '<span aria-hidden="true" data-icon="e"')
.replace(/onclick='deletetodo\(this\)'><\/span>-->/, 'onclick="deletetodo(this)"></span>');
}
This is the (rather large!) chunk of JS that controls this. Any ideas what's wrong? Or maybe a better way of changing these icons around?
Thanks!
I would say: you're are doing it wrong. Using a string / regex replacement method is not the right way to go imho.
Instead of doing those replacement use DOM methods, i.e.:
someElement.setAttribute('data-icon', 'f');
someElement.setAttribute('alt', 'Urgent');
A simple example can be found here: http://jsbin.com/iwakof/1/edit
I know this isn't a direct answer to your question, but trust me this is the way to go
That's awesome that you are learning JavaScript. Nice job. But, I'm quite glad that you posted this question as it looks like you could use a couple of pointers.
The answer to your question is - yes there is a much simpler way to achive this effect - which I will get to shortly. But first - I notice that at the bottom of your todo app you include a library called JQuery
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
This library will be of huge help to you, not only in the function you describe above, but to the majority of the code you have written. You will end up with much cleaner and self explanatory code.
http://jquery.com/
Basically what JQuery allows you to do, is to manipulate the state of the DOM. You definatly want to begin here.
Here is small sample which shows a check box who can be checked or unchecked, and on change, have an element shown' or hidden as desired.
http://jsfiddle.net/m4vGE/5/
Please - do take the time to have a look into JQuery - its a great first step you can take to increase your produtivity and reduce complexity in your JavaScript
Also - as a side note, if you find yourself using js to build HTML with strings, the answer is invariably "there is a better way"
If all you are trying to do is change icons based on a checkbox being checked or no, you could do something like this.
function getVisibility()
{
var temp = document.getElementById("iconName").style.visibility;
return temp;
}
function switchIfChecked()
{
var current = getStyle();
if( current == "visible" )
{
document.getElementById("iconName").style.visibility = "hidden";
}
else
{
document.getElementById("iconName").style.visibility = "visible";
}
}
<div id="iconName" style="visibility: visible">INSERT ICON IMG here</div>
What the above does is that it makes the div of the icon visible or hidden. Ofcourse you will need to have two divs and then set either or to hidden or visible.
With what you are doing currently, you are not really making the browser do anything.
Try to use the global option of Regex (have a look at the g after the second slash):
// ...
.replace(/<tr class=\"list-row done\"/g, '<tr class=\"list-row\"')
// ...
Here is an example.
From developer.mozilla.org:
global: Whether to test the regular expression against all possible
matches in a string, or only against the first.

innerhtml workaround for IE td elements?

I have the following function:
<script type="text/javascript">
function changeText(elem){
var oldHTML = document.getElementById(elem).innerHTML;
var newHTML = "<span style='color:red'>" + oldHTML + "</span>";
document.getElementById(elem).innerHTML = newHTML;
}
</script>
And the following HTML:
<table>
<tr>
<td id = "foo">bar</td>
</tr>
</table>
This throws a "unknown runtime error" (just in IE) which googling has since taught me that table elements are read-only in IE with innerHTML.
I've tried finding workarounds but they don't target my specific problem, which is just that I want to make the word "bar" red. I don't want to change the word "bar" to something else. Purely a color change.
Is there any way to do this without a complex and slow DOM function and without having to change any of the other HTML markup on the page? This is a table with a form in it, and if the surfer submits the form with an error, the "errored" fields should turn red. It has to be able to execute multiple times because it's possible for a surfer to mess up more than one field.
Thanks for any advice.
Why not just change the cell to have color:'red' :
var td = document.getElementById(elem);
td.style.color = 'red';
Couple ways to go about it. Here are some quick ones to get you going -- or until someone else comes with a cleaner/better method.
I prefer the following: define an error class in css:
.errorHighlight { color:red;}
Then for the javascript:
function changeText(elem){
document.getElementById(elem).className="errorHighlight";
}
function changeTextBack(elem){
document.getElementById(elem).className="";
}
This assumes that you don't have any classes set already. If you do you may need to read the name, and append the error class with a space.
Again, there are a lot of ways to approach this and you want to pick the one best suited for your application.

Removing everything before dash from each H4 tag

this sounds really simple and stupid..but I'm having a hard time removing the content before each dash from each H4 element on my page....i've been trying to do this with Jquery/Javascript.. Any insight?
Here's a sample of my HTML code:
<h4>California-Medical Research</h4>
<h4>Florida-Industrial</h4>
<h4>Atlanta-Computers</h4>
I'm trying to have my code cycle through each occurance of <h4> and remove everything before the dash...so the desired result will look like this:
Medical Research
Industrial
Computers
Thanks!
Assuming your layout's consistent with dashes you could do this:
​$("h4").text(function(i, t) { return t.substring(t.indexOf('-') + 1); });​​​​​​​​​
Since jQuery 1.4+ .text() takes a function, making this very clean. You can give it a try here.
Try this :
$.each($('h4'), function(i){
var content = $(this).html();
content = content.split('-')[1];
$(this).html(content);
});

Categories