I need to write a function that will search all the content in my HTML page for a specific string, and if it finds it then change the color of the text.
Is this possible?
Thanks
You could do that :
CSS :
.someclass {
color: red;
}
Javascript :
$('p:contains('+yourstring+')', document.body).each(function(){
$(this).html($(this).html().replace(
new RegExp(yourstring, 'g'), '<span class=someclass>'+yourstring+'</span>'
));
});
Note that this would make problems if yourstring is in a tag or an attribute.
Demonstration
Be careful to run this code before you attach handlers to your paragraphs (or the elements inside which could contain yourstring, for example links).
The problem with dystroy's answer is that it will overwrite the entire HTML, so if you have any handlers within a node containing your text, they will be removed.
The correct solution is to use text ranges to update only the text itself, not all of the HTML around it. See Highlight text range using JavaScript
And for fun, there is a built-in method window.find that works in FF and Chrome. It's not in the standard though and will only find one at a time. Just like ctrl+f.
window.find("anything");
JQuery Find and change style of a string >> Only Copy Paste and run :)
$('#seabutton').click(function()
{
var sea=$('#search').val();
var cont=$('p').val();
alert(cont);
$('p:contains('+sea+')').each(function()
{
/* $(this).html($(this).html().replace(new RegExp(sea, 'g'),'<span class=someclass>'+sea+'</span>'));
*/ $(this).html($(this).html().replace(
new RegExp(sea, 'i'), '<span class=someclass>'+sea+'</span>'
));
});
});
$('p').click(function()
{
$(".someclass").css("color", "black");
});
$('#search').blur(function()
{
$(".someclass").css("color", "black");
});
})
</script>
<style type="text/css">
.someclass {
color: red;
}
</style>
</head>
<body>
<!-- Select Country:<select id="country" name="country">
</select>
<table id="state" border="1">
</table> -->
<br>
Enter Text:<input type="text" id="search"/><input type="button" id="seabutton" value="Search"/>
<div id="serach">
<p>This is ankush Dapke
</p>
</div>
</body>
</html>
Related
I am attempting to implement a "Light/Dark Mode" feature to a real time text editor, however due to the use of srcdoc the iframe refreshes and removes any CSS applied to it via JQuery. I would like to be able to keep the CSS within the iframe's contents.
I've attempted to make use of .css() to the contents of my frame, which works, but since I'm refreshing the frame on each keyUp event, the CSS is refreshed and no longer applied.
Appending the stylesheet also seems to result in it being "cleared" when refreshing.
How can I get the CSS to stay applied to the frame?
HTML
<div>
<textarea id="text-input" onkeyup="refresh()" placeholder="Enter your code here.."></textarea>
</div>
<div>
<iframe id="output-display"></iframe>
</div>
Javascript
function refresh(){
var input = document.getElementById('text-input').value;
document.getElementById('output-display').srcdoc = input;
}
$(document).ready(function(){
$('#output-display').contents().find('body').css('color', 'white');
});
EDIT:
The aim of this is to be a Real Time Editor, allowing a user to enter some code on the left (text area) and the result to be displayed on the right (iframe)
Ok so I think you don't actually have to use an iframe to accomplish what you are going for here. You could just use a regular html element and set the content at every keypress. Please see the code snippet below for reference:
var isDark = false;
function toggleTheme() {
if(isDark) {
$('#output-display').css({'background-color': 'black', 'color': 'white'});
isDark = false;
} else {
$('#output-display').css({'background-color': 'white', 'color': 'black'});
isDark = true;
}
}
function refresh() {
var inputValue = document.getElementById('text-input').value;
var parsedHtml = $.parseHTML(inputValue, document, true);
$('#output-display').html($(parsedHtml));
}
toggleTheme();
refresh();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="button" onclick="toggleTheme()" value="Toggle Theme" />
<br>
<textarea id="text-input" onkeyup="refresh()" placeholder="Enter your code here.."></textarea>
</div>
<div>
<div style="border: 1px solid black; width: 500px; height: 300px" id="output-display" disabled></div>
</div>
EDIT: added a theme toggle to illustrate further how you could use this.
EDIT2: added .parseHTML so you can add html to the input and render it
I have a list of divs on a page. I have a filter system that fills in a 'data-' element with a possible list of values.
Example:
<div data-myvalues="value1,value2,value3"></div>
<div data-myvalues="value2,value3"></div>
<div data-myvalues="value1,value2"></div>
<div data-myvalues="value1,value3"></div>
Then I have some jQuery that tries to filter based on some selections that include the values in the data-myvalues attribute. However, the jQuery filter does not quite work because I think it sees the values as including the comma (,) in the value.
How, in jQuery, would I filter based on an if the divs include the values or not. I am currently using the jQuery
$("div[data-myvalue*='value1']").show();
But it seems to now quite work for some reason it will work if the data-myvalues only has one value in it, the jQuery works, but if there are multiples separated by a comma, the jQuery does not work.
I have a JS fiddle here with a simple sample code I was messing with to get the proof of concept to work.
https://jsfiddle.net/ebz3cmjn/1/
Is there a better way to list values on an element then filter them?
Thanks in advance.
You can try something like this:
$(document).ready(function() {
$.each($('div'), function(i, v){
var values = $(v).data('myvalues');
if(values.indexOf('value1') != -1) {
$(v).show();
} else {
$(v).hide();
}
})
});
And html content with data values:
<div data-myvalues="value1,value2,value3"></div>
<div data-myvalues="value2,value3"></div>
<div data-myvalues="value1,value2"></div>
<div data-myvalues="value1,value3"></div>
Hope this helps.
The data attribute takes JSON object which you can take advantage of.
Given the following element:
<input data-nations='["anothernation", "nationman", "country"]' type="text" value="Germany">
You could filter the desired elements based on the target value:
var targetNation = "nationman";
$("input[data-nations]")
.filter(function () {
// Returns the list as array
return $(this).data("nations").indexOf(targetNation) > -1;
})
.css("background-color", "blue");
Note the two differences between the quotes:
// will parse correctly
data-nations='["anothernation", "nationman", "country"]'
// will NOT parse correctly since it will be treated as plain text
data-nations="['anothernation', 'nationman', 'country']"
Try with .not() like the following way:
$(document).ready(function(){
$("input[data-me*='nationman']").css("background-color", "yellow");
$("input").not("[data-me*='nationman']").css("background-color", "red");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input data-me="nationality" type="text" value="Chinese">
<input data-me="nationman" type="text" value="English">
<!--This doesn't work with more than one value-->
<input data-me="nationman,country" type="text" value="Germany">
<input data-me="anothernation" type="text" value="Norwegian">
<p>This selector selects all input fields with the attribute name that contains the string 'nation'.</p>
You can also loop through all elements with .each():
$(document).ready(function() {
$('[data-myvalues]').each(function(){
var values = $(this).data('myvalues');
if(values.includes('value1'))
$(this).show();
else
$(this).hide();
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-myvalues="value1,value2,value3">value1,value2,value3</div>
<div data-myvalues="value2,value3">value2,value3</div>
<div data-myvalues="value1,value2">value1,value2</div>
<div data-myvalues="value1,value3">value1,value3</div>
Checkout the snippet;
I have modified you code a litte bit, hope this will help to get your answer;
This is a little bit tricky answer, but you can easily understand the code
$(document).ready(function(){
var el = $('input');
el.each(item =>{
var attr = el[item].dataset
if(attr.me.match(/nationman/)){
el[item].setAttribute('style', 'background-color:yellow')
}else{
el[item].setAttribute('style', 'background-color:red')
}
})
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input data-me="nationality" type="text" value="Chinese">
<input data-me="nationman" type="text" value="English">
<!--This doesn't work with more than one value-->
<input data-me="nationman, country" type="text" value="Germany">
<input data-me="anothernation" type="text" value="Norwegian">
<p>This selector selects all input fields with the attribute name that contains the string 'nation'.</p>
</body>
</html>
Try This I think it will work
$(document).ready(function(){
$("input[data-me*='nationman']").css("background-color", "yellow");
$("input").not("[data-me*='nationman']").css("background-color", "red");
});
I have a label which displays an IP address:
<label id="internet_ipaddr" class="label_s1"></label>
What I want to do is display a div, #youareoffline if the label is empty. This was suggested as an implementation but after playing around I can't get it to work:
if (string.IsNullOrWhiteSpace(#internet_ipaddr)) {
$(#youareoffline).show();
}
The code you've attempted to use looks like a mix of C# (string.isNullOrWhiteSpace()) and pseudo code, not valid JS.
To make this work you can check if the element has any children (text nodes or otherwise) using the is(':empty') method, then show the relevant element. Try this:
if ($('#internet_ipaddr').is(':empty')) {
$('#youareoffline').show();
}
#youareoffline { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="internet_ipaddr" class="label_s1"></label>
<div id="youareoffline">You are offline</div>
Also note that you can make the JS more succinct, although arguably harder to read, by using toggle():
$('#youareoffline').toggle($('#internet_ipaddr').is(':empty'));
you can easily do this using jQuery.
HTML
<label id="label1"></label>
<div id="div1" style="display: none; color: red;">You are off line.</div>
jQuery
var labelText = $("#label1").text();
if (!labelText) {
$("#div1").show();
}
Is it possible to use "::-webkit-input-placeholder" with jQuery to set a color for the placeholder text?
Something like this:
$("input::-webkit-input-placeholder").css({"color" : "#b2cde0"});
You can't really modify pseudo-selectors with JavaScript. You'll have to modify an existing a <style> element.
If possible, make a class:
.your-class::-webkit-input-placeholder {
color: #b2cde0
}
And add it to the element:
$('input').addClass('your-class');
If you don't have a stylesheet, and want to inject CSS dynamically you can use the following:
$('body').append('<style>.my_class::placeholder{color:red}</style>')
Just use my_class and the color for the placeholder.
It's handy to have a general purpose function:
function change_placeholder_color(target_class, color_choice) {
$("body").append("<style>" + target_class + "::placeholder{color:" + color_choice + "}</style>")
}
Usage:
change_placeholder_color('.my_input', 'red')
Just add this. It will inherit the color in input[type=text]:focus new color
.your-class ::placeholder{ color: inherit;}
Here is an example of dynamically setting pseudo-element styles using jQuery – it's a matter of creating a <style> element, setting its text content to the desired style declarations, and appending it to the document.
Here is a simple single-page example:
<!doctype html>
<html>
<head>
<title>Dynamic Pseudo-element Styles</title>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script>
$(document).ready(function() {
createStyles();
$('#slider-font-size').on('change', createStyles);
function createStyles() {
// remove previous styles
$('#ph-styles').remove();
// create a new <style> element, set its ID
var $style = $('<style>').attr('id', 'ph-styles');
// get the value of the font-size control
var fontSize = parseInt($('#slider-font-size').val(), 10);
// create the style string: it's the text node
// of our <style> element
$style.text(
'::placeholder { ' +
'font-family: "Times New Roman", serif;' +
'font-size: ' + fontSize + 'px;' +
'}');
// append it to the <head> of our document
$style.appendTo('head');
}
});
</script>
</head>
<body>
<form>
<!-- uses the ::placeholder pseudo-element style in modern Chrome/Firefox -->
<input type="text" placeholder="Placeholder text..."><br>
<!-- add a bit of dynamism: set the placeholder font size -->
<input id="slider-font-size" type="range" min="10" max="24">
</form>
</body>
</html>
I was using MaterializeCSS; I used Jquery to update CSS for input fields like this
$(".input-field").css("color", themeColor);
$(".input-field>.material-icons").css("color", themeColor);
$(".input-field>label").css("color", themeColor);
See Result:
https://codepen.io/hiteshsahu/pen/EXoPRq?editors=1000
I have this hidden link, which is needed for other purposes:
<span id="notitle" style="display: none;">
</span>
The link is generated dynamically and automatically includes the title attribute. But I'd like to remove the title attribute since the value is copied when the user copy-pastes surrounding text.
I thought of using javascript. This is what I've got so far:
<html>
<head>
<script type="text/javascript">
function notitle() {
var mylist=document.getElementById("notitle")
var listitems= mylist.getElementsByTagName("a")
for (i=0; i<listitems.length; i++) {
listitems.setAttribute("title", "");
}
}
</script>
</head>
<body onLoad="notitle()">
<p>Before hidden link:
<span id="notitle" style="display: none;">
This Link should have no title attribute
</span>
After hidden link.</p>
</body>
</html>
But doesn't work. I guess it's about listitems.setAttribute("title", "");
Any idea? Cheers :)
listitems is the collection, so your code is probably throwing an error.
Anyway, you want:
listitems[i].setAttribute("title", "");
First of all, you need to select the one specific item by using listitems[i], second, I think you can do it as simple as this:
listitems[i].title = ""
You need to add the i index:
listitems[i].setAttribute("title", "");
You're doing
listitems.setAttribute("title", "");
i times.
Add an array index into the list.