How to store the value of an attribute inside a variable using html, javascript? - javascript

I have a line <meta property="product:price:amount" content="3.05"/>
in a large html file.
I need to store the value of content inside a variable, so that I may access it globally.
How can I do that?

Just catch it with querySelector to get it's content attribute.
const content = document.querySelector('meta').content;
console.log(content);
<meta property="product:price:amount" content="3.05"/>
In case of multiple meta tags:
const elems = document.querySelectorAll('meta');
let content = Array.from(elems).find(v => v.content).content;
console.log(content);
<meta property="product:price:amount"/>
<meta property="product:price:amount"/>
<meta property="product:price:amount" content="3.05"/>

To very specifically get the meta tag you are after (event if there are multiple meta tags):
var variable = document.querySelectorAll('meta[property="product:price:amount"]')[0].content;

If there is only one item then simply
document.getElementsByTagName("meta")[0].content

For a single meta tag:
var myGlobal = document.querySelector('meta[content]').getAttribute('content');
document.body.textContent = myGlobal;
<meta property="product:price:amount" content="3.05"/>
If you have a lot of tags:
var contentArray = [];
document.querySelectorAll('meta[content]').forEach(function(meta){
contentArray.push(meta.getAttribute('content'));
});
document.body.textContent = contentArray.join(' - ');
<meta property="product:price:amount" content="3.05"/>
<meta property="product:quality:amount" content="9.25"/>
<meta property="product:id:amount" content="1.0"/>
If you want to be more specific about the tag you can change the selector:
...querySelector('meta[property="product:price:amount"][content]')...
Read more about selectors https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors

Related

document.creatElement can't show utf8 chars

I create label elem with document.crteateElement and I set text value to elem with .innerHTML but on page browser don't show utf-8 characters correct I see only '?' in black rectangle.
This my hrml charset:
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-9">
<META HTTP-EQUIV="Content-language" CONTENT="tr">
I use this function for convert :
GetChar(char) {
return unescape(decodeURIComponent(char))
}
and this is my value
const target= '${this.GetChar('İ')}stikamet'
then here is I set value to label elem
var elem = document.createElement('label)
elem.innerHTML = target
What is the corrent way show this characters on browser ?
Try this instead of your current meta-tags
<meta charset="UTF-8">
EDIT:
The following HTML displays your example-char fine for me:
<html>
<meta charset="UTF-8">
<body>
<label>İ</label>
</body>
</html>

How do I expose images from json data

I have looped over some json and have pulled urls from the data. The thumbnail data looks like:
{href: "https://link/medium.jpg"}
href: "https://link/medium.jpg"
>__proto__: Object
How can I expose each url so the actual images display on the browser not the links. This is my code. console.log(o._links.thumbnail) is the data I receive from above:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=\, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Fetch Json</title>
</head>
<body>
<p>
thumbnail:
</p>
<script>
const url =
"https://s3-us-west-2.amazonaws.com/example.json";
async function getThumbnail() {
const response = await fetch(url);
const data = await response.json();
var art = data._embedded.artworks;
art.forEach(function(o) {
//console.log(o._links.thumbnail);
var img = document.createElement("image");
img.src = o._links.thumbnail; //set the value equal to the href
document.querySelector("body").appendChild(img);
});
}
getThumbnail();
</script>
You need to manipulate the DOM, something like this.
let elem = document.createElement("img");
elem.src = o._links.href;
document.getElementById("placehere").appendChild(elem);
Reference:
Adding an img element to a div with javascript
Try to append image elements and set the src attribute to the value of href
this is more general than the code I posed before:
1) Loop thru your json
2) create image element
var img = document.createElement("image");
img.src = o._links.thumbnail; //set the value equal to the href
document.querySelector("body").appendChild(img);

Routing(?) in Vanilla JS

I need my webite to display info in a certain language, based on a query in my webite's URL (e.g. www.website.com/index.php?country=FR). How can I do that with vanilla JS and not React/Angular?
My approach:
1) JS recognizes a query in the URL (in this case- 'country=FR') and then appends a js file, which has neccessary french words in it defined by variables.
2) JS in my script tag that's in the HTML file, appends the main page markup text with template literals in it.
3)
I don't know, whether the browser fails to either fetch the language file itself or its variables. At the moment it does not render anything.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./js/main.js"></script>
</head>
<body>
<script>
const template= `
<h1>Good Morning: ${goodmorning} </h1>
<h2>Good Evening: ${goodevening} </h2>
<h3>My name is: ${mynameis}</h3>`
function markupAppend() {
$('body').html(template);
console.log('Markup loaded')
}
markupAppend()
</script>
</body>
</html>
=========================
Main.js
var domain = window.location.href;
var FRString = domain.includes("country=FR");
var ESString = domain.includes("country=ES");
if (FRString) {
$('head').append(`<script src="./Language_files/FRENCHwords.js" />`)
}
if (ESString) {
$('head').append(`<script src="./Language_files/SPANISHwords.js" />`)
}
=========================
FRENCHwords.js
const goodmorning = 'Bonjour';
const goodevening = 'Bonsoir';
const mynameis = 'Mon nom est';
=========================
SPANISHwords.js
const goodmorning = 'Buenos dias';
const goodevening = 'Buenas tardes';
const mynameis = 'Mi nombre es';
No errors displayed, the page is just not rendering...
In Your main.js file, you are using domain.includes, it only returns the domain name but not the entire URL. You can use window.location.href.includes for this.
Instead of: domain.includes("country=FR");
Try: window.location.href.includes("country=FR");

Fnd links containing particular string in href and remove href between slashes with javascript only

I have a use case, where i have to select all <a>, containing string in url like "/web/local" and remove "/web/local" from all href of all these links.
Note: i can't use jQuery. I can use either pure js or YUI.
Thanks in advance.
See comments inline:
let phrase = "/web/local";
// Get all the links that contain the desired phrase into an Array
let links = Array.prototype.slice.call(document.querySelectorAll("a[href*='" + phrase +"']"));
// Loop over results
links.forEach(function(link){
// Remove the phrase from the href
link.href = link.href.replace(phrase, "");
});
// Just for testing:
console.log(document.querySelectorAll("a"));
Some Link
Some Link
Some Link
Some Link
Some Link
In order to get /set correctly the href attribute you need to use getAttribute/setAttribute:
document.querySelectorAll('a[href*="/web/local"').forEach(function(ele) {
ele.setAttribute('href',
ele.getAttribute('href').replace('/web/local', ''));
console.log(ele.outerHTML);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
Link 1
Link 2
<script>
var string = '/web/locale/';
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
var link = links[i].getAttribute('href');
link = link.replace(string, '');
links[i].setAttribute('href', link);
}
</script>
</body>
</html>

Regular Expression to select part in HTML

I have requirement to extract meta property from scrolled HTML source code. After scrolling HTML code contains as follows
Example:
<meta property="og:site_name" content="asasasas">
<meta property="og:title" content="asajhskajhsaksp;" />
<meta property="og:image" content="images.cxs.com/2014/09/modit1.gif?w=209" />
Here I want to get the content of only where meta property="og:image" ie result should be only
images.cxs.com/2014/09/modit1.gif?w=209
was it so difficult to use jquery
$('meta[property="og:image"]').attr('content')
As #Biffen said, don't use regex to parse html.
If you have the said string in a variable you can use querySelector() like
var html = '<meta property="og:site_name" content="asasasas" /><meta property="og:title" content="asajhskajhsaksp;" /><meta property="og:image" content="images.cxs.com/2014/09/modit1.gif?w=209" />';
var el = document.createElement('div');
el.innerHTML = html;
var meta = el.querySelector('meta[property="og:image"]');
console.log(meta.content);
document.getElementById('result').innerHTML = meta.content;
<div id="result"></div>
If it is part of the current page then
var meta = document.querySelector('meta[property="og:image"]');
console.log(meta.content);
document.getElementById('result').innerHTML = meta.content;
<meta property="og:site_name" content="asasasas"/>
<meta property="og:title" content="asajhskajhsaksp;" />
<meta property="og:image" content="images.cxs.com/2014/09/modit1.gif?w=209" />
<div id="result"></div>
You can use the approach suggested by Arun, however there may be user agents that don't support the Selectors API or don't support the required features (e.g. IE8). In that case, you can use getElementsByTagName and a plain old for loop.
var node, nodes = document.getElementsByTagName('meta');
for (var i=0, iLen=nodes.length; i<iLen; i++) {
node = nodes[i];
if (node.getAttribute('property') == 'og:image') {
// do something with content
console.log(node.content);
}
}
the above will work in any browser in use and doesn't require any external library.

Categories