Select and Replace an embedded style with jQuery - javascript

Is it possible to select and replace an embedded styles background path with jQuery? I'm having trouble getting this to work.
<script>
$(document).ready(function($) {
function myReplaceFunc() {
var $str = $('style');
$str.replace('wcsstore', 'mytest');
}
myReplaceFunc();
});
</script>
<style>
#test{
background: url("/wcsstore/***/en_GB/images/suppliershop/ecomheader.jpg");
}
</style>
<section id="test">Test 1</section>
<section id="test2">Test 2</section>
Any help much appreciated.

Aside from the issue with calling replace() on a jQuery object, your approach to this is flawed. While it's possible to amend the content of <style> tags with JS, it's very far from the best solution.
Instead, you should set the background-image on the element directly using the css() method. You can provide a function to this method which receives the current value as an argument. You can then call replace() on that - as you currently are - to update the value. Try this:
$(document).ready(function($) {
function myReplaceFunc() {
$('#test').css('background-image', function(i, bg) {
return bg.replace('wcsstore', 'mytest');
});
}
myReplaceFunc();
});
#test {
background: url("/wcsstore/***/en_GB/images/suppliershop/ecomheader.jpg");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="test">Test 1</section>
<section id="test2">Test 2</section>

Use .text() chained to jQuery() to get, set the .textContent of the element
$str.text($str.text().replace('wcsstore', 'mytest'));

1- get the background image url from css applied
var bg = $('#test').css('background-image');
bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
2- change the url
var new_url = bg.replace('wcsstore','mytest');
3- replace the url
$('#test').css('background-image', 'url(' + new_url + ')');

Related

How can I make a javascript that sets the background color of an element to the innerhtml color code?

As I'm making a style template for a website, I'd like to make span elements that from example blocks with a background color. Example:
<span class='colblock'>#FF0000</span>
should result in a block with color code #FF0000 (Red) as background color.
Currently, the following css and JS code is being used (relevant bits)CSS
<style>
span.colblock{
margin:8px;
padding:8px;
display:block;
border:1px solid black;
border-radius:2px;
width:66px;
}
</style>
Javascript (On page bottom, just before body)
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
$("colblock").each(function() {
var ccode = $(this).html();
$(this).css("background-color", ccode);
});
</script>
IMO, this is supposed to work, but it does not. Can someone elighten me?
While selecting element by class use . operator. You have error here:
$(".colblock").each(function() {
^ //missed '.' dot
Use following:
$(".colblock").each(function() {
var ccode = $(this).html();
$(this).css("background-color", ccode);
});
In css also you having typo:
<span.colblock{
^ //===> should be removed
See working Example
Use $(this).text() instead of $(this).html()
$(".colblock").each(function() {
var ccode = $(this).text();
$(this).css("background-color", ccode);
});
And in your css <span.colblock should be like this: span.colblock
To select a class, you should use $(".ClassName"), here it will be $(".colblock").
$("colblock") will select elements with tag name "colblock".
Your jquery link seems dead.
src="//code.jquery.com/jquery-migrate-1.2.1.min.js"
This one works as I tested:
src="http://code.jquery.com/jquery-1.2.1.min.js"
Not using JQuery
var the_Span = document.getElementById("colblock");
var span_Text = the_Span.innerText;
the_Span.style.backgroundColor = span_Text;

jQuery get text in element but ignore style tags

I have javascript code that tests if a div has some non whitespace text content.
This works but it cannot differentiate between text content or style tag declarations within the div and the test fails when there is no text content but a style tag with css data.
Question is how to test for empty text content while ignoring the style tag?
HTML:
<div id='test1'>
<div> </div>
</div>
<div id='test2'>
<div> </div>
<style>
.style1{
border:1px;
}
</style>
</div>
Javascript:
// Works
if($('#test1').text().trim().length==0){
alert('test1 has no content!');
}
// Does not work due to style1 declaration within style tag within div
if($('#test2').text().trim().length==0){
alert('test2 has no content!');
}
Test URL:
http://jsfiddle.net/sLDWB/
One option is cloning the element and removing the style tags:
$.fn.isTextless = function() {
var txt = this.first()
.clone()
.find('style')
.remove()
.end()
.text();
return $.trim(txt).length === 0;
}
if ( $('#test2').isTextless() ) {
alert('test2 has no content!');
}
http://jsfiddle.net/5Z3M4/
You can just use a common class for all the elements you need to check, loop through them using each, store the initial HTML, remove the style tag, do your check and restore the initial HTML. Like so :
$('.testdiv').each(function() {
var divHtml = $(this).html();
$(this).find('style').remove();
if($(this).text().trim().length==0){
alert( $(this).attr('id') + ' has no content!');
}
$(this).html(divHtml);
});
http://jsfiddle.net/sLDWB/1/
Subtract the style tag's length with the actual length.
Try,
if($('#test1').text().trim().length==0){
alert('test1 has no content!');
}
if($('#test2').text().trim().length - $('#test2 style').text().trim().length ==0){
alert('test2 has no content!');
}
DEMO
Use following javascript code
document.getElementById('test2').innerText
The style tag is meant to go in the head of a page. Why do you even have .style1 there if no element uses style1? If you want to change the style of a div, either do <div style="border: 1px;"> or make a style declaration in the <head> part of the HTML page.
In short, you shouldn't ever have a <style> tag outside of <head>.

change background color of div with jquery that has an !important tag

Using a plugin that calls a .jsp that uses its own stylesheet hosted externally (it's a yelp embed - trying to manipulate the look of it). The one element I'm trying to change has an !important tag on it, and I can't seem to change it...
I tried
<script type="text/javascript">
$('.elementToChange').css({'background-color':'black'});​
</script>
to no avail. Ideas?
It looks like in more up-to-date versions of jQuery (at least 1.7.2 and higher) you can simply set the css:
$('#elementToChange').css('background-color', 'blue');
See http://jsfiddle.net/HmXXc/185/
In older versions of jQuery and Zepto you had to clear the css first:
// Clear the !important css
$('#elementToChange').css('background-color', '');
And then reset it using:
$('#elementToChange').css('background-color', 'blue');
Or in a one-liner:
$('#elementToChange')
.css('background-color', '')
.css('background-color', 'blue');
See http://jsfiddle.net/HmXXc/186/.
Original answer:
Note: this may be a bad idea, as it will remove any other inline styles
I would edit the style attribute directly
$('.elementToChange').attr('style', 'background-color: blue !important');
http://jsfiddle.net/RichardTowers/3wemT/1/
Here is your solution:
http://jsfiddle.net/irpm/bdhpp/2/
The idea is to add the class:
$('.elementToChange').addClass('blackBg');
You can manipulate !important css by using following steps, either you can use inline-css or Internal css or you can load your own external css after the order of that preloaded css, it will help you to override that css with your custom one.
<html>
<head>
<!--
//First Solution
//PreloaderCSS
//YourCustomCSS
//Second Solution
Internal CSS -->
</head>
<body>
<!--
Third solution
//Inline CSS
->
</body>
</html>
You can use the following function:
function replaceBGColorImportant(element,newColor){
var styles = element.getAttribute('style');
styles = styles?styles.split(';'):[];
var newStyles = [];
styles.map(function(x){
if (x.split(':')[0] != "background-color")
newStyles.push(x);
});
newStyles.push('background-color:#'+newColor+' !important');
element.setAttribute('style',newStyles.join(';'));
}
Execute as follows:
replaceBGColorImportant(document.body,'#009922');
Via regular expression:
https://jsfiddle.net/7jj7gq3y/2/
HTML:
<div class="elementToChange" style=" background-color: yellow !important; width: 100px; height: 100px;"></div>
JavaScript:
var setImportantStyle = function(element, attributeName, value) {
var style = element.attr('style');
if (style === undefined) return;
var re = new RegExp(attributeName + ": .* !important;", "g");
style = style.replace(re, "");
element.css('cssText', attributeName + ': ' + value + ' !important;' + style);
}
setImportantStyle($('.elementToChange'), 'background-color', 'red');

jquery get styles from an id

does anyone know how can i get all styles applied to an id using jquery (so i can reuse it later in another tag)? something like
css:
div#myid{
width:100px;
height:100px;}
so i can later do something like:
for (var parts in $('#myid').css())
alert ('all parts of the style' + parts);
$('#myid').attr('class') returns a string of the classes.
You should be able to figure it out from here.
var classes = $('#myid').attr('class').split(' ');
for(var c in classes)
{
alert(classes[c]);
}
It is not jquery but works well:
var style = window.getComputedStyle(document.getElementById('myid'), null);
alert(style.color);
You can replace document.getElementById('myid') by $('#myid').get(0) if you really want to use jquery here.
This works either for a style given by CSS or directly applied on the element with the style attribute.
Not sure.. I had tried attr('class') before and it returned empty. trying now again produces the same result (nearly). i suppose attr('class') in jquery isnt exactly the same as styles defined via id. try running this, let me know if you get different results please:
<html>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
alert($('#myid').attr('class')); // returns 'empty'
var classes = $('#myid').attr('class').split(' ');
for(var c in classes){
alert(c); // returns 0
}
});
</script>
<style>
#myid {
width:100px;
height:100px;
background:red;
}
</style>
<body>
<div id="myid"></div>
</body>
</html>

How to get CSS of a clicked div using jQuery?

Can anybody know how to get border-color of a div using jQuery.
$("#divcolor").click(function (){
alert("dsf");
var divcolor = $(this).css("border-color");
alert(divcolor);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="divcolor" style="border:#333333 solid 1px;" >
This is the target
</div>
In divcolor variable I am not getting anything.
Using the CSS jQuery function like you did:
http://docs.jquery.com/CSS/css#name
But read this paragraph:
Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.
Your mistake is elsewhere. That code works on Chrome and IE.
border-color isn't working for me either (on Firefox), but this works:
$(this).css("border-top-color")
http://jsbin.com/ezefu
I always consider it better practice to work with CSS classes instead of CSS direct. Then you could have something like:
$(this).hasClass("MyClassWithTheBorderColorStyleInIt");
You can write like this
$("#divcolor").click(function() {
var divcolor = $(this).css("border");
divcolor = divcolor.substring((divcolor.indexOf(' ') + 1), divcolor.length);
divcolor = divcolor.substring((divcolor.indexOf(' ') + 1), divcolor.length);
alert(divcolor);
});
$("#divcolor").click(function (){
var divcolor = $(this).css("borderColor");
alert(divcolor);
});
Try this one:
$("#divcolor").click(function (){
alert("dsf");
var divcolor = $(this).css("border-color");
alert(divcolor);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="divcolor" style="border:1px solid; border-color:#333333;" >
This is the target
</div>

Categories