Replace All innerhtml text with Javascript - javascript

I've been trying for hours and I've looked a lot of samples on StackOverflow, but I can't fix my simple script.
I grabbed DOM with jQuery
var color = $('#bscontainer').html();
and now the content of color is:
<img src="resources/P/Blue_BG_2Col.png" id="bg">
<img src="resources/P/Blue_Content_2Col.png" id="content">
<img src="resources/P/Blue_Title_ExchangeRate.png" id="title">
<img src="resources/P/Blue_SubTitle_2Col.png" id="subtitle">
<img src="resources/P/Blue_Disclaimer_Disclaimer.png" id="disclaimer">
My idea is to change all the Blue to Green, and I already try this:
curColor="Blue";
newColor="Green";
t=color.replace(curColor,newColor);
It simply doesn't works. Any ideas?

To answer your question directly, replace in javascript when it takes a string parameter as the needle, only replaces the first instance. To replace all instances within a string, use a global regular expression:
str.replace(/Blue/g, 'Green');
You really ought to just modify the src attributes of the img tags though. That is the more proper way to attack this. Changing the html like you are trying to will lose any events or data bound to the DOM elements.

So basically you want to find each image in your color element and replace Blue with Green in the src attribute -- This is one way you can do it:
var color = $('#bscontainer');
color.find('img').each(function(){
curColor="Blue";
newColor="Green";
this.src = this.src.replace(curColor,newColor);
});
No need for the .html() part of your code...

Use a callback function to actually update the HTML, and use a regular expression (object) to replace all instances at once:
$('#bscontainer').html(function (i, str) {
curColor = new RegExp("Blue","g"); // global replace
newColor = "Green";
return str.replace(curColor, newColor);
});

Related

How can I get link text from CSS to string object?

I have HTML tag with link in background style and I want this link to be a string in my JS file. How can I do that?
<div class="bmlistt" style="background: url('b.ppy.sh/thumb/845746.jpg';)"></div>
You can grab the it using this:
var bg = $("div.bmlistt").css('background');
bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
How about the following:
const imageElement = document.getElementsByClassName('bmlistt')[0];
let image = imageElement.style.background.replace('url("', '').replace('")', '');
console.log(image);
<div class="bmlistt" style="background: url(b.ppy.sh/thumb/845746.jpg)"></div> <!-- Fix ";" in style attribute -->
No need for big libraries. querySelector to get the div. I would use its style.background or style.backgroundImage property. The latter of those only contains the image itself, and not any other background css you might specify in a real life scenario, possibly making it easier to extract the url.
Unfortunately with your specific HTML that doesn't work, because of an error in the CSS (the semicolon). So in that case you have to parse the style attribute as text, rather than relying on the style object property, which contains the browser's interpretation of your CSS. Both solutions are shown below.
var theDiv = document.querySelector('.bmlistt');
console.log(theDiv.style);
// Doesn't work because of error in the CSS. Otherwize this would do it.
var css = theDiv.style.backgroundImage;
console.log(css.substr(5, css.length - 7));
var attr = theDiv.getAttribute('style');
// This, if you know the length of the 'overhead' around the url, or
// a regular expression.
console.log(attr.substr(17, attr.length - 20));
<div class="bmlistt" style="background: url('b.ppy.sh/thumb/845746.jpg')"></div>

Jquery replaceWith keep onclick

How can I keep onclick="" value with JQuery replaceWith ? I'm making a assets system that preload every image and put it on a Javascript image() object, and using a special data attribute for img urls
<img data-assets="images/test.png" onclick="alert('test')">
turn into : (using jquery replaceWith)
<img src="assets/images/test.png">
What I want:
<img src="assets/images/test.png" onclick="alert('test')">
My code:
$("[data-assets]").each(function() {
$(this).replaceWith(Game.Preloading.Assets.Images[$(this).data('assets')]);
});
How can I fix that ? Thanks
While iterating over each [data-assets] element, you could set the corresponding onclick attribute before replacing the element:
$("[data-assets]").each(function() {
var $newImg = $(Game.Preloading.Assets.Images[$(this).data('assets')]);
$newImg.attr('onclick', $(this).attr('onclick'));
$(this).replaceWith($newImg);
});
However, it would be better to just add a src attribute on the existing element rather than replacing it:
$("[data-assets]").each(function() {
this.src = $(Game.Preloading.Assets.Images[$(this).data('assets')]).attr('src');
});
Ideally, you should be using unobtrusive JavaScript and avoiding the inline JavaScript event listeners, but both of the above snippets should work.
I think you would be better off to simple query for your attribute, then use the each method to update the SRC attribute on each matched element.
Im on my phone so a more detailed answer is difficult...
But here goes
$("[data-assets]").each(function(){ $(this).attr("src", Game.Preloading.Assets.Images[$(this).data('assets')]); });

Set div background color without using ID

Is possible change color of background my div using JavaScript without using ID? And how?
Html code is:
<div class="post" onmouseover="test(this)">
JS code is:
function test(item){
alert("Hi :-)");
}
Have you tried
function test(item){
item.style.backgroundColor = "red";
}
Since item is the actual div you're triggering this event on you won't need an ID to style the element.
A really easy (inline) solution would be the one below.
<div class="post" onmouseover="javascript:style.backgroundColor = 'red';">
Content blabla
</div>
I would personally rather do all of this inside a JS file but hey this works too.
You can loop through the DOM with JavaScript, but you'll have a better time of it if you're using JQuery. You'll want to invest some time learning about selectors:
http://api.jquery.com/category/selectors/
http://www.w3schools.com/jquery/jquery_ref_selectors.asp.
You'll be looking for something like:
function test(){
var element = $('div');
}
As people have shared in the comments, without a unique identifier, you'll have a rough time, especially as new elements are added to the page.

Avoiding extra use of span

My question is that I have an html code <p> Hello World </p>
And want to change the css of every letter using JavaScript. Essentially, I will change the background color to make an animation. Is there a way to do this without making a span or some sort of tag around every letter and going through all that struggle?
I have my string array with colors and a method to call the correct color (data-index attribute).
Thanks!
EDIT: I have the entire word changing color and thought of an idea by making a function that iterates over the indexes of the innerHTML string and assigns a data-index to the letter's span by editing the function provided below by Cymen. Is this a good approach?
No, you will need to use a tag that supports background-color. You can easily wrap a string of characters in spans like so:
function wrapInSpans(string) {
return '<span>' + string.split('').join('</span><span>') + '</span>';
}
You would have to use a JavaScript function to wrap each character in a <span>.
window.onload = function() { // when everything loads, run the function
var elem = document.getElementById( "someId" );
var text = elem.innerHTML; // get the <p>'s text content
elem.innerHTML = ""; // then make the <p> empty
for( var i=0; i<text.length; i++ ) { // for each character in the text
elem.innerHTML += "<span>"+text[i]+"</span>";
}
};
Remember to change "someId" to the id of your <p> element.
You can access each individual character inside the for loop with text[i].
This would take quite a bit of code to spell out completely, but, if it's very important in your case to not actually add some type of wrapping element, then I believe this would be possible via a dynamically generated background image.
Roughly the steps would be:
Create a Range with a start and end around each character in the .textContents of the element you care about.
.getBoundingClientRect() on each range to get its rendered dimensions.
Draw rectangles of the desired color to a <canvas>.
Export the <canvas> as a data URI.
Use the data URI as a background-image.
Repeat for each block displayed element that you care about.
Be advised that there will, no doubt, be various edge cases in this approach and possible browser support limitations. Obviously just wrapping each character is a much simpler.

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>");
}

Categories