Replace part of HTML string with Javascript or PHP - javascript

I need to replace part of the HTML tag for displaying YouTube videos:
<div class="pretty-embed" data-pe-videoid="IL5AbXBqzwk" data-pe-fitvids="true"> </div>
with direct link to YouTube image while keeping ID which is defined in data-pe-videoid attribute:
<img src="http://img.youtube.com/vi/YiF7e7m2jPo/sddefault.jpg">
If I break it in two parts, I would need to replace
<div class="pretty-embed" data-pe-videoid="
with
<img src="img.youtube.com/vi
and
" data-pe-fitvids="true"> </div>
with
/sddefault.jpg">
I'm looking for a solution with PHP or jQuery/vanilla JavaScript. I tried to experiment with PHP & regular expression but without success.
Any help would be appreciated.

Solution using jQuery to add/append an image to each div since its not clear what you mean by "replace part of html":
(function($) {
$(function() {
$('[data-pe-videoid]').each(function() {
var el = $(this);
// append img
el.append($('<img src="http://img.youtube.com/vi/' + el.data('pe-videoid') + '/sddefault.jpg">'));
});
});
})(jQuery);
Alternatively replace instead of append:
el.replaceWith($('<img src="http://img.youtube.com/vi/' + el.data('pe-videoid') + '/sddefault.jpg">'));

Related

Change Part of URL String of an image

I am wondering if there is a way to change the last part (name of image) in a URL string using jQuery.
Here is what I have:
http://domain.com/m/m62RLwnqkpPuKl13jSxURBg/80.jpg
and here us what /i need it to be:
http://domain.com/m/m62RLwnqkpPuKl13jSxURBg/140.jpg
Question update:
I need to target and replace the name of the image only, which is "80" in this case, without using the rest of the URL, as the URL path will be different for each image.
<div class="image">
<img alt="" src="http://thumbs3.ebaystatic.com/m/m62RLwnqkpPuKl13jSxURBg/80.jpg" itemprop="image">
</div>
replace
var s='http://domain.com/m/m62RLwnqkpPuKl13jSxURBg/80.jpg';
s=s.replace(/(.*)\/.*(\.jpg$)/i, '$1/40$2')
alert(s);
FIDDLE
OK, I found out the solution. If looking for the same thing, here it is:
$('.image').children().each(function () {
$(this).html(function (i, html) {
return $(this).html().replace(/80.jpg/g, '140.jpg');
});
});
credit goes to #Eliseu Monar
Thank you!

Fill div with html using javascript/jquery

here is my problem:
I have a div:
<div id="legend"></div>
and I want to fill it, under certain conditions, with this other code:
<p>Showing results....
Key:
<img src="/...."><=1
<img src="/..."><=2
<img src="/..."><=3
<img src="/..."><=4
<img src="/..."><=5
<p>
As you can see this is a legend and the main issue I think is that I have double quotes that cannot be easily included using for instance the solution here:
Fill div with text
Thanks for your help!
By my understanding, you are trying to do something like this:
$("#legend").text("Your HTML here");
To insert HTML, you should use .html(), HOWEVER it would be far more efficient to just use Vanilla JS like so:
document.getElementById('legend').innerHTML = "Your HTML here";
Now, you also mention having problems with double-quotes. Well, there are two possible solutions.
1: Use single-quotes around your string: '<img src="/..." />'
2: Escape the quotes: "<img src=\"/...\" />"
And one more thing: If those newlines are actually in your HTML to insert, you can't have a multi-line string in JavaScript. You have two options here too:
1: Escape the newline:
"<p>\
Hello, world!\
</p>"
2: Concatenate:
"<p>\n"
+"Hello, world!\n"
+"</p>"
Assemble your html code in a variable according to your conditions (which we do not know), then use html() to set it to the element.
var yourHtml = "your html";
$("#legend").html("yourHtml");
As for dealing with the quotes, you can either use single quotes in variable, such as:
var yourHtml = '<img src="/yourimgr.png">';
or you can escape the double quotes:
var yourHtml = "<img src=\"/yourimgr.png\">";
Store your paragraph html in some string
var str= <p>write your complete code here</p>
$('#legend').html(yourconditionSatisfies?str:'')

How to store a HTML snippet and insert it later in the document?

Is there a way to store a HTML snippet in a variable using Javascript or jQuery like this? (obviously it's a non-working an example)
var mysnippet = << EOF
<div class="myclass">
<div class="anotherclass">
Some dummy text
</div>
</div>
EOF
And then insert it in the document using jQuery:
mysnippet.append($('#someelement'));
EDIT:
Please, read this before answering of commenting: What I have is a raw HTML snippet inside my JS file, and I need to store it in a Javascript variable using something like that EOF construction. I need to avoid putting it between quotation marks.
If it's not possible using Javascript and/or jQuery, then the question has no solution.
Just get the HTML code of the div you want by var content = $('#somediv').html(); and then append it to some div later on ! $('#otherdiv').append(content);
$().html(); delivers the HTML Content of that div. documentation: http://api.jquery.com/html/
$().append(<content>); appends the Content to a special div. documentatoin: http://api.jquery.com/append/
You could use javascript templates like ejs and haml-coffee.
You could write:
var mysnippet = "<div class='myclass'>"+
"<div class='anotherclass'>"+
"Some dummy text"+
"</div>"+
"</div>";
and then insert is using the append function (which takes the snippet as argument).
Yes. Fiddle example
JavaScript
var html = '<b>Bold</b>'
$('.anotherclass').append(html);
HTML
<div class="myclass">
<div class="anotherclass">
Some dummy text
</div>
</div>
Unfortunately nothing like << EOF is available. Here's one solution:
$el = $('<div />')
.addClass('myClass')
.append(
$('<div />')
.addClass('anotherclass')
.text('Foo Bar')
);
Thinking on the same issue I have found this discussion. What I have in mind is to put a hidden textarea, containing the html, and then retrieving the html from there.
Thus there will be no conflicts with doubled DOM ids, since textarea content isn't rendered as html.
For those who come across this as I have...
You may wish to use the new
<template>
tag in HTML5.
It still doesn't store the HTML in the JavaScript unfortunately :(

Javascript onClick change background picture of div

My ultimate goal is to change the background of a div through clicking on the sampla picture.
First I wrote this:
<a onclick="document.getElementById('sp').style.background="url('/assets/castle.png')"">...<a>
but it didn't work. I noticed that the problem was usage of multiple " and '. So put the function into a script tag:
<script type="text/javascript">
var pic="";
function showP(pic) { document.getElementById('sp').style.background='url(pic)';};
</script>
<a onclick="showP(/assets/castle.png)"><img src="/assets/castle.png" width="50px" height="50px"></a>
As supposed by seeing /assets dir, this is a rails app. I also tried o use jQuery selectors like $("#sp").css() or dropping the variable altogether and trying the function as:
function showp1() { document.getElementById('sp').style.cssText='background: transparent url(/assets/castle.png) no-repeat 0 0;'}
to try out solutions proposed in questions with similar titles but none did work. Whatever I try, on the html source, the portion showP(/assets/castle.png)" below is marked red:
<a onclick="showP(/assets/castle.png)"><img src="/assets/castle.png" width="50px" height="50px"></a>
Are there any suggestions?
Avoid putting JS in your HTML code. Use unobtrusive event listeners. They are very easy in jQuery:
$('#clickMe').on('click', function() {
$('#changeMe').css('background-image', 'url(http://placehold.it/200x200/ff0000)');
})
See this Fiddle.
Try this:
<script type="text/javascript">
function showP(pic) {
document.getElementById('sp').style.background = 'url(' + pic + ')';
};
</script>
<a onclick="showP('/assets/castle.png')">
<im src="/assets/castle.png" width="50px" height="50px" />
</a>
You needed to pass a string to the showP function in the onclick handler, which should be in quotes. You're passing a string into the function, which is in the pic variable being passed into the function. You want that string variable's value to be concatenated with the URL rule for the background style.
the background image URL does not require quotes. Try:
<a onclick="document.getElementById('sp').style.background='url(/assets/castle.png)'">...<a>
As others have said, you do seem to have an issue with quotes. You can check out my working example on jsFiddle.

best way to inject html using javascript

I'm hoping that this isn't too subjective. I feel there is a definitive answer so here goes.
I want to create this html on the fly using JS (no libraries):
Play
Mute
<div id="progressBarOuter">
<div id="bytesLoaded"></div>
<div id="progressBar"></div>
</div>
<div id="currentTime">0:00</div>
<div id="totalTime">0:00</div>
using javascript. I know I can do this using createElement etc but it seems extremely long winded to do this for each element. Can anyone suggest a way to do this with more brevity.
I do not have access to a library in this project....so no jquery etc.
Keep your markup separate from your code:
You can embed the HTML snippets that you'll be using as hidden templates inside your HTML page and clone them on demand:
<style type="text/css">
#templates { display: none }
</style>
...
<script type="text/javascript">
var node = document.getElementById("tmp_audio").cloneNode(true);
node.id = ""; // Don't forget :)
// modify node contents with DOM manipulation
container.appendChild(node);
</script>
...
<div id="templates">
<div id="tmp_audio">
Play
Mute
<div class="progressBarOuter">
<div class="bytesLoaded"></div>
<div class="progressBar"></div>
</div>
<div class="currentTime">0:00</div>
<div class="totalTime">0:00</div>
</div>
</div>
Update: Note that I've converted the id attributes in the template to class attributes. This is to avoid having multiple elements on your page with the same ids. You probably don't even need the classes. You can access elements with:
node.getElementsByTagName("div")[4].innerHTML =
format(data.currentTime);
Alternatively, you can act on the HTML of the template:
<script type="text/javascript">
var tmp = document.getElementById("tmp_audio").innerHTML;
// modify template HTML with token replacement
container.innerHTML += tmp;
</script>
Shove the entire thing into a JS variable:
var html = 'Play';
html += 'Mute';
html += '<div id="progressBarOuter"><div id="bytesLoaded"></div><div id="progressBar"></div></div>';
html += '<div id="currentTime">0:00</div>';
html += '<div id="totalTime">0:00</div>';
Then:
document.getElementById("parentElement").innerHTML = html;
if you want theN:
document.getElementById("totalTime").innerHTML = "5:00";
You can use
<script type="text/javascript">
function appendHTML() {
var wrapper = document.createElement("div");
wrapper.innerHTML = '\
Play\
Mute\
<div id="progressBarOuter"> \
<div id="bytesLoaded"></div>\
<div id="progressBar"></div>\
</div>\
<div id="currentTime">0:00</div>\
<div id="totalTime">0:00</div>\
';
document.body.appendChild(wrapper);
}
</script>
If you live in 2019 and beyond read here.
With JavaScript es6 you can use string literals to create templates.
create a function that returns a string/template literal
function videoPlayerTemplate(data) {
return `
<h1>${data.header}</h1>
<p>${data.subheader}</p>
Play
Mute
<div id="progressBarOuter">
<div id="bytesLoaded"></div>
<div id="progressBar"></div>
</div>
<time id="currentTime">0:00</time>
<time id="totalTime">0:00</time>
`
}
Create a JSON object containing the data you want to display
var data = {
header: 'My video player',
subheader: 'Version 2 coming soon'
}
add that to whatever element you like
const videoplayer = videoPlayerTemplate(data);
document.getElementById('myRandomElement').insertAdjacentHTML("afterbegin", videoplayer);
You can read more about string literals here
edit: HTML import is now deprecated.
Now with Web Components you can inject HTML using an HTML import.
The syntax looks like this:
<link rel="import" href="component.html" >
This will just load the content of the html file in the href attribute inline in the order it appears. You can any valid html in the loaded file, so you can even load other scripts if you want.
To inject that from JavaScript you could do something of the likes of:
var importTag = document.createElement('link');
importTag.setAttribute('rel', 'import');
importTag.setAttribute('href', 'component.html');
document.body.appendChild(importTag);
At the time I am writing this, Chrome and Opera support HTML imports. You can see an up to date compatibility table here http://caniuse.com/#feat=imports
But don't worry about browsers not supporting it, you can use it in them anyway with the webcomponentsjs polyfill.
For more info about HTML imports check http://webcomponents.org/articles/introduction-to-html-imports/
If you don't need any validation for your syntax (which is what makes createElement() so nice) then you could always default to simply setting the innerHTML property of the element you want to insert your markup inside of.
Personally, I would stick with using createElement(). It is more verbose but there are far less things to worry about that way.
If performance is a concern, stay away from innerHTML. You should create the whole object tree using document.createElement() as many times as needed, including for nested elements.
Finally, append it to the document with one statement, not many statements.
In my informal testing over the years, this will give you the best performance (some browsers may differ).
If HTML is ever declared in a variable, it should be simple and for a very specific purpose. Usually, this is not the right approach.
here's 2 possible cases :
Your HTML is static
Your HTML is dynamic
solution 1
In this case, wrap your HTML in double quotes, make it a string and save it in a variable. then push it inside HTML, here's a demo 👇
HTML
<div id="test"></div>
JavaScript
let selector = document.querySelector("#test");
let demo_1 = "<div id='child'> hello and welcome</div>"
selector.innerHTML = demo_1;
solution 2
In this case, wrap your HTML in back ticks, make it a template literal and save it in a variable. then push it inside HTML,
here, you can use variables to change your content. here's a demo 👇
HTML
<div id="test"></div>
JavaScript
let selector = document.querySelector("#test");
let changes = 'hello and welcome'
let demo_1 = `<div id='child'>${changes}</div>`
selector.innerHTML = demo_1;
You can concatenate raw HTML strings (being careful to escape text and prevent XSS holes), or you can rewrite jQuery (or something similar)
I have a situation where I pass text into a third party library, but if my model isPrivate, I'd like to add an element to the text.
return { id: item.id, text: (item.isPrivate == true) ? "<i class=\"icon-lock\" title=\"Private group.\"></i> " + item.label : item.label };
This creates issues with the way the third party library builds up its markup.
This is never a good idea, but third party libraries are there so that we don't have to write everything ourselves. In a situation like this, you have to rely on passing markup though javascript.
When i find a proper solution to this, I will give you an update

Categories

Resources