Target closest class if string contains value - javascript

I have a localstorage item that gets stored in the page head, the const for this is also in the page head so that it gets loaded once, the below code duplicates for all product card items that load onto the category page, this code is added inline in script tags into the product card include, so that the metafield can collect each products unique metafield value, to make the example simpler I've just put "hello" where the metafield would be.
What I'm trying to do is check if "string" includes the value "hello", and if it does the script should find the closest class called "container" and add html on to the end of it.
In < head > tag:
const string = 'hello my name is';
In product card include:
window.onload = function() {
if (string.includes("hello")) {
$(target).closest('.container').after('<div class="pass">some message</div>');
}
}
I haven't found any errors in the code but I'm sure there's something obvious to someone who has more experience, would be great if anyone can help out!
Here is my latest attempt to fix the issue, still nothing is being added in html..
<script>
window.onload = function() {
const string = 'hello my name is';
const div = document.getElementById('6204142256316');
if (string.includes("hello")) {
div.insertAdjacentHTML('afterbegin', '<div class="pass">some message</div>');
}
}
</script>
<div id="6204142256316"></div>

Have the target be some selector the uniquely identifies the script element that each “product card” contains. For example, each script element inside of the “product card” could have an id of product-card-script-${PRODUCT_ID}.
The function set to window.onload does not necessarily know that it is in the context of the product card when loaded.
This answer assumes that you have control of adding an id attribute to each script added to each product card.

The solution was to make any liquid render outside the script - so this now works
<script>
window.onload = function() {
const string = 'hello my name is';
const div = document.getElementById('6204142256316');
if (string.includes("hello")) {
div.insertAdjacentHTML('afterbegin', '<div class="pass">some message</div>');
}
}
</script>
<div id="6204142256316"></div>
To show what I was doing wrong:
{{ product.id }}.insertAdjacentHTML.......
Even though liquid is rendered prior to JS it seems this should always be like the below:
const div = document.getElementById('{{ product.id }}');
div.insertAdjacentHTML...........
Once I did that it worked perfectly.

Related

How do I initialize a whole div from LocalStorage in HTML without breaking it with "/"?

So, I am creating a "favorites page" using local storage to store the items that you click to add to favorites, the items are normal cards like this (just an example):
<div class="card__box">
<div class="heart-wrapper"></div>
<div onclick="link('index.html?BI=auditoria')">
<div class="card__icon"><img src="./assets/icons/auditoria.png"></div>
<div class="icon__text">
<span class="icon__header"><strong>Auditoria</strong></span>
</div>
</div>
</div>
I am saving them in local storage with outer.HTML
(how localStorage is saving them)
the thing is, when I try to show them in the HTML the LocalStorage give the value with some alterations like bars "/" and "\n". (like this):
"<div class="card_mini_box"> \n <div class="times-mini-wrapper"><a href="#" class="fas fa-times" id="auditoria" aria-hidden="true">\n <div onclick="link('index.html?BI=auditoria')">\n <div class="card_mini_icon"><img src="./assets/icons/auditoria.png">\n <div class="icon_mini_text">\n <span class="icon_mini_header">Auditoria\n \n \n "
As u can see all messed up.
I am saving them in localstorage like this:
let favorites = JSON.parse(localStorage.getItem('favorites')) || []
const source = favdiv.outerHTML;
favorites.push(source);
localStorage.setItem('favorites', JSON.stringify(favorites));
(favdiv is the whole div selected)
And I am trying to show them in HTML like this:
var output = document.getElementById("mini__cards");
var element = document.createElement("div");
element.textContent = localStorage.getItem('favorites');
output.appendChild(element);
please help me I tried a lot of different methods and none of them worked.
Already Tried saving with innerHTML and also tried to put them in html with innerHTML as well.
for this method to work, some details were missing when saving and showing the favorites.
When getting the div, use innerHTML, it gets the elements inside the selected div, so there is no risk of duplicating IDs.
Before saving, removing breaking lines.
When showing data, remember to use a loop to show all stored data.
Your code would look like this to save:
var favorites = JSON.parse(localStorage.getItem("favorites")) || [];
var favdiv =
document.getElementById("divs").innerHTML.replace(/(\r\n|\n|\r|\s\s)/gm, "");
favorites.push(favdiv);
localStorage.setItem("favorites", JSON.stringify(favorites));
Using replace, I remove line breaks, with \n and \r.
And to view the saved divs, I use a forEach to go through the entire array, create a template and show its content as the last element:
var favorites = JSON.parse(localStorage.getItem("favorites"));
var output = document.getElementById("mini__cards");
favorites.forEach((favorite) => {
let tempElement = document.createElement("template");
tempElement.innerHTML = favorite.trim();
output.append(tempElement.content);
});
More detailed explanation about above code: https://stackoverflow.com/a/35385518/20815693
This is the result for your case, using jquery this code can be reduced and easier to handle DOM. I hope I have helped you.

Extract HTML link from inside DOM header resource (without ID or class)

I have the following code structure on a site:
<link rel="amphtml" href="http://example.com/?amp"></head>
I am looking to extract the html link only on pages where the "amphtml" rel value appear. I tried the following code but it breaks the application on urls where that tag does not appear.
var ampLink_txt = document.querySelector("link[rel=amphtml]").getAttribute("href");
I don't have access to change the HTML document, do I can't add any ID's or classes. Can anybody point me in the right direction?
.querySelector may return null if nothing is found. You should check first if it's null:
const ampLink = document.querySelector("link[rel=amphtml]")
if (ampLink) {
const ampLink_txt = ampLink.getAttribute("href")
// ...
}
See https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

Checking to see if page title is in array via jQuery

I've created semi-dynamic page titles on a static site by using the following on each page (for example):
<?php $title="Example"; ?>
And added this to my header file:
<title>Company Name Here<?php if ($title!="") { echo " | $title"; } ?></title>
That part is working well.
Now, I would like to use jQuery to check if a page title for the ACTIVE page is in an array so that (if it is) I can apply a class to a navigation element or two. And, if it not in the array, I'd remove that class. Like so (in partial pseudocode):
if $(title) of currently visible page is in this array(about, page2, page3) {
$('a#idname').addClass('selected')
} else {
$('a#idname').removeClass('selected')
}
Maybe there's a better way to do this. I'm open to suggestion. I'm just not very clear on the syntax for determining:
What page is currently loaded
How to use some identifier for the current page to change the class of an element on the page after page load. I know how to do it on click, but as soon as the page loads, the class goes away.
Any help greatly appreciated. Thanks in advance!
You can retrieve the document's title by accessing the title property on the document object, document.title. In order to get the portion of the string after the pipe, |, you could simply split the title on the | character and then get the second element in the returned array.
If the page's title is "Company Name Here | About" like in your question, then document.title.split('|') would return the array ["Company Name Here ", " About"], therefore .split('|')[1] would return the string "About".
Use the .indexOf() method in order to check if the title string is in the array titleArray and then add/remove the class accordingly.
Here is a basic example:
var title = document.title.split('|')[1];
var titleArray = ['About', 'Page2', 'Page3'];
if (title && titleArray.indexOf(title.trim()) > -1) {
$('span').addClass('selected');
} else {
$('span').removeClass('selected');
}
.selected { color: #f00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>Company Name Here | About</title>
<span>The title is in the array if this is red.</span>

How do I give an ID to part of the contents of a <title> tag?

I have a title tag that looks something like this:
<title>My Page Title - Photo #3</title>
I want to use JavaScript to change the numeric part of it, without having to hard code the "My Page Title - Photo #" string which is generated server side.
I tried wrapping the number in a span so that I could change the contents of the span:
<title>My Page Title - Photo #<span class="photoid">3</span></title>
But it seems HTML is not allowed in the title tag. I'd really like to pursue the class approach if possible as that would allow me to use a line of jquery such as this:
$('.photoid').html(new_photoid);
Did I mention that the photoid appears in several places on the page, which is why I want to be able to use this oneliner to change them all at the same time? For example:
<p>A paragraph also containing the number <span class="photoid">3</span></p>
A title can only have text, so you need to parse it out.
document.title = document.title.replace(/\d+$/, "new value");
title can't be set like that,
it's not a child of .html
some thing like
var num = 3;
document.title = "foo "+num
to set the title, then reuse num for these photoids.
Use the jQuery onDocumentReady syntax:
$(function () {
var elements = $('.contains_photoid');
elements.html(elements.html().replace("3", "4"));
$(document).attr('title', $(document).attr('title').replace("3", "4"));
});
You can't see the title change in this example, but that is the syntax. See Changing the page title with Jquery
The "3" and "4" can be changed to anything, so you can create the page with a unique character string in place of the real ID in order to easily replace it if it appears in text with numbers already in it.
http://jsfiddle.net/ZmXj5/1/
Javascript
var photoID = 355; //this assumes you have some code where you set this photoID value
var title = document.title;
title = title.substr(0,title.lastIndexOf('#')+1);
document.title = title+photoID;
See this fiddle for proof: http://jsfiddle.net/xrkhA/
(I used a div content because you can't use title in jsfiddle)
You can either use, but $('title') will fail in IE8
document.title="new title";
or
$('title').html('new title');
or
$(document).attr('title','new title');

change part of a link with javascript in a specific div only

Hi I need to edit some links on a page. Using the below code works but causes other problems on the page. I need the code to only affect elements with a certain input id. I also can't just replace the links as a query will be dynamically added to the end of each link. So in summary i just need to replace parts of all links with an input id "btnViewDetails". Any help would be great I'm very stuck. Cheers
<script language="javascript">
document.body.innerHTML = document.body.innerHTML.replace(/JobSeekers/g,'mobile');
document.body.innerHTML = document.body.innerHTML.replace(/JobPositionDetail.aspx/g,'JobPositionDetail_Mobile.aspx');
</script>
var someVariable = document.getElementsByClassName('btnViewDetails');
(you should use class instead of ID, if it is not a unique value).
someVariable is now an array holding all elements with class name btnViewDetails.
Now replace the text you want to replace only on the href values of you elements (you will have to loop over them):
for (i = 0; i < someVariable.length; i++) {
someVariable[i].href // do your replaces here
}

Categories