Replacing Text with Images When Text is Loaded via PHP - javascript

so I'm currently working in the development of site and I'm wanting to replace text in divs with images, I've seen a few examples on here however they don't repeat for multiple strings of the same text or the javascript loads before the PHP and doesn't change the text.
<div class="text">text1</div>
<div class="text">text2</div>
<div class="text">text1</div>
I'm needing text1 to replace with image1 and text2 to replace with image2 etc etc. What would the best way to do this ?
I forgot to include that it's a CMS so I don't have access to the PHP directly, just the HTML templates it uses.

This snippet loops over the .text elements and gets the text# value from each element. Then extracts the number of each text and uses it to create a new image. Whenever the image has been loaded with the correct src it will remove the text and replace it with the image.
const textElements = document.querySelectorAll('.text');
for (const textElement of textElements) {
let text = textElement.textContent;
let numberOfText = text.split('text').pop();
const image = new Image();
image.addEventListener('load', event => {
textElement.removeChild(textElement.firstChild);
textElement.append(image);
});
image.src = `/image${numberOfText}`;
}
<div class="text">text1</div>
<div class="text">text2</div>
<div class="text">text1</div>

Related

How to target container of a div in Javascript?

I created a very easy javascript line to change the image on hover, https://designordering.com/wink/ however, I would like to make this hover effect on the entire container instead just on the image that has the image and the "Say Hi" text. Which is actually working now because I added it directly on the HTML tag.
<div class="sayHi" onhover="contact" onmouseover="document.getElementById('myImage').src='./img/face-wink.png'" onmouseout="document.getElementById('myImage').src='./img/face.png'">
<span style="font-size:1.5rem; font-family:Roboto, sans-serif; font-weight:600; padding-right: 15px;">Say Hi</span>
<img class="face" id="myImage" src="./img/face.png" alt="face" height="80px">
</div>
However, I want to move this script to an external JS file and I have a hard time finding the solution for it.
Can you help me, please?
I am trying to target the container div instead of the image tag. Or to find a solution how can I move this to an external JS file
onmouseover="document.getElementById('myImage').src='./img/face-wink.png'" onmouseout="document.getElementById('myImage').src='./img/face.png'"
You could do this by referring to the div element in the javascript code
const sayHiDiv = document.querySelector(".sayHi");
const myImage = document.getElementById("myImage");
sayHiDiv.addEventListener("mouseover", e => myImage.src = "./img/face-wink.png");
sayHiDiv.addEventListener("mouseout", e => myImage.src = "./img/face.png");
Edit
If a more modular approach is needed (if you can't access the element in the javascript) then you can define a function instead
function changeImage (div, src)
{
div.querySelector("img").src = src;
}
The function can then be used to simplify the HTML
<div class="sayHi" onmouseover="changeImage(this, '.img/face-wink.png');" onmouseout="changeImage(this, '.img/face.png');" >
<!-- span and img -->
</div>

How can I shorten this jQuery .load() code?

I have a script on a page referencing a function in an external script (it converts a Markdown file to HTML and displays it as the innerHTML of a div):
$(document).ready(function() {
let input = document.getElementById('input');
let output = document.getElementById('output');
$("#input").load("convertme.md", function() {
output.innerHTML = convert(input.innerText);
});
});
with:
<div id="input" style="display: none;"></div>
<div id="output"></div>
This way, convert() works fine, the original markups become proper HTML tags. But I want to shorten the code, by merging the two div into one, say <div id="content"></div>, as the only innerText area to be handled by the function (so that I wouldn't have to hide the pre-conversion text). I changed the function to:
$(document).ready(function() {
let content = document.getElementById('content');
$("#content").load("convertme.md", function() {
content.innerHTML = convert(content.innerText)
});
});
This way, however, the conversion is imperfect: it fails to convert the Markdown paragraphs into p, such that all the paragraphs following each header become embedded inside <h1>...</h1> etc instead of <p>...</p>. Why?
Or is there a better way to merge the input and output div?

Convert the HTML content to a string and print it in a text file

I am trying to print the HTML content in a .txt file. I tried using innerHTML, innerText and innerContent. But all this are printing with all the tags along with it.
Please refer to the screenshots
Image 1
Image 2
Image 1 is how I wanted to show it, but image 2 is how it actually appears.
Each text block seems to be in a <pre>. Create an array from those elements and map the text from each then join with line break(s).
Something like:
const pre = document.querySelectorAll('.content pre')
const txt = [...pre].map(el => el.textContent.trim()).join('\r\n\r\n')
console.log(txt)
<div class="content">
<pre>Text block 1</pre>
<pre>Text block 2</pre>
<pre>Text block 3</pre>
</div>
It is because of when you save an html file in .text format, you actually have a encoded html code (see HTML Entities), and you need to decode it for browser so the browser will not treat it as a string and detects the tags and could render it.
NOTE that Directly convert a text to a render-able html code is s a security bug (XSS), but if you have to, you can use methods like what is showing in this answer.
Or try unescape(str) method.
try
function get_content() {
var html = document.getElementById("txt").innerHTML;
document.getElementById("txt").innerHTML = html.replace(/<[^>]*>/g, "");
}

trying to grab image url within div's children

I'm making an extension that grabs an image URL within the "uCW" div on an HTML page.
Currently, I have:
var uCW = jNode.closest("div._q7o");
var image = uCW[0].children[1].getElementsByTagName("img")[0].src;
console.log(image);
That finds the image by going into the div/children and pulling the image. Unfortunately, this method is problematic, since it stops working if the children change, which they regularly do.
Instead, I want to select the image by searching the div and all its children (there are a lot of them) for the first image/string that starts with "https://external" (all the images I want start this way, and that doesn't seem to change.)
This is what I tried:
var uCW = jNode.closest("div._q7o");
var image = $(uCW).find([name^="https://external"]).src;
console.log(image);
This doesn't work. The console just prints "undefined."
You could do it like this, if ucw is a classname (if it's an id, you would write $("#ucw") instead):
var image = $(".ucw").find('[src^="https://external"]').attr("src");
console.log(image);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ucw">
<img src="https://external/1.jpg"/>
</div>
If your images have a name attribute with the source of the image as value, you can also adjust your attempt to fetch the images via their name attribute like you did:
var image = $(".ucw").find('[name^="https://external"]').attr("src");

Find src attribute value of <img> tag in a Javascript string

I have been trying to get the 'src' in img tags inside a javascript variable that contains a block of HTML code dynamically generated/assigned.
Eg:
var post_body = "<div>This is an image <img src='abcd.jpg' /> and this is a paragraph <p>hi there</p> Here we have another image <img src='pqrs.jpg' /></div>"
the content of the 'post' variable is not predefined and it is dynamic and the HTML code in it always changes. To get the src of the image in it, I did the following. But it does not always work for me.
var firstimg = $(post_body).find("img:first").attr("src");
I was trying to get the first image of a blog post from the blog post's content but this does not work for some posts having images. How can this be done using javascript or jQuery without failing?
Using plain JavaScript, dump the HTML into a temporary element and extract it:
var div = document.createElement('div');
div.innerHTML = post_body;
var firstImage = div.getElementsByTagName('img')[0]
var imgSrc = firstImage ? firstImage.src : "";
// or, if you want the unresolved src, as it appears in the original HTML:
var rawImgSrc = firstImage ? firstImage.getAttribute("src") : "";
Change $(post_body) to $(post)
Try
var post = "<div>This is an image <img src='abcd.jpg' /> and this is a paragraph <p>hi there</p> Here we have another image <img src='pqrs.jpg' /></div>";
var firstimg = $(post).find('img:first').attr('src');
Perhaps you can try adding id to img tag and then access it.
var oImg = document.getElementById('myImg');
var attr = oImg.getAttribute('src');
This is a pure js solution.
Late but, if don't want the images to be loaded use the below.
var div = document.createElement('template');
div.innerHTML = post_body;
if you create div element the remote images are loaded the moment you insert innerHTML, template prevents the requests.

Categories