I want to get text of background-image URL.
Expect Output:
123
http://123.com
(It is empty)
But Actual Output:
$('#p1').html($('#bg1').css('background-image').replace('url(','').replace(')','').replace(/\"/gi, ""));
$('#p2').html($('#bg2').css('background-image').replace('url(','').replace(')','').replace(/\"/gi, ""));
$('#p3').html($('#bg3').css('background-image').replace('url(','').replace(')','').replace(/\"/gi, ""));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
I know that this function can be implemented by manipulating strings.
Is there any other way?
I know this css is not specification, But I want to write GreaseMonkey UserScript to hack other Website.
Solved:
This style.backgroundImage saved me! Thank!
$.fn.extend({
getBackgroundUrl: function () {
let imgUrls = [];
$(this).each(function (index, ele) {
let bgUrl = ele.style.backgroundImage || 'url("")';
bgUrl = bgUrl.match(/url\((['"])(.*?)\1\)/)[2];
imgUrls.push(bgUrl);
});
return imgUrls.length === 1 ? imgUrls[0] : imgUrls;
}
});
$('p').html($('a').getBackgroundUrl().join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p></p>
You can do that a lot easier with a single regular expression: match the url and the opening parentheses, capture the single or double quote, then capture and lazy-repeat characters until you get to the next single or double quote:
const getUrl = str => str.match(/url\((['"])(.*?)\1\)/)[2];
$('a').each((_, a) => console.log(getUrl(a.style.backgroundImage)));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
No need for a big library like jQuery just to select elements, you can do it in vanilla JS quite easily too:
const getUrl = str => str.match(/url\((['"])(.*?)\1\)/)[2];
document.querySelectorAll('a').forEach((a) => {
console.log(getUrl(a.style.backgroundImage));
});
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
Related
How do I use a checkbox in JS/jQuery to toggle just between 2 numbers?
I want unchecked to always be $0 and checked to always be $100. The code below comes close. I'm looking to use str.replace as opposed to switching divs using display:none.
Code:
function myFunction() {
let str = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML = str.replace("$0", "$100");
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String</h2>
<p>The replace() method searches a string for a specified value, or a regular expression,
and returns a new string where the specified values are replaced.</p>
<p id="demo">$0</p>
<input type="checkbox" onclick="myFunction()" value="Try It">
</body>
</html>
function myFunction() {
const element = document.getElementById('demo')
element.innerText = element.innerText === '$0' ? '$100' : '$0'
}
I would like to rename a h1 text in the header for any single page, is it possible with a script?
The line of the title is:
Like this
I wrap in a page load event and then use the closest known selector
If you have class="titoloheader" the code is even simpler than using
div[data-row=middle] h1
If you want to change only on pages with /articoli/ you can test pathname:
const url = new URL(location.href);
if (url.pathname.split("/").indexOf("articoli") !=-1) {
document.querySelector("h1.titoloheader").innerText = "Hello"
}
})
If you want to change on page-id-X, you can do this:
Vanilla JS
const pageTitles = {
"41": "Hello",
"44": "Goodbye",
"47": "Ciao",
"3": "Arriverderci",
"313": "Hey",
"316": " Bye",
"318": " This is silly",
"50": "The end"
};
const changeHeader = () => {
let id = [...document.body.classList] // all the classes of the body tag
.filter(classStr => classStr.startsWith("page-id")); // find the one that starts with page-id
if (id.length)[, , id] = id[0].split("-") // if found (an array) grab the last part after last -
if (id && Object.keys(pageTitles).includes(id)) { // do we find that ID in the list
document.querySelector("h1.titoloheader").innerText = pageTitles[id]; // change the header
}
};
window.addEventListener("load", changeHeader); // when the page loads
<body class="home page-template-default page page-id-47 logged-in admin-bar no-customize-support ct-loading" data-link="type-1" data-forms="classic">
<div data-row="middle" data-columns="1">
<div class="ct-container">
<div data-column="middle">
<div data-items="">
<div class="ct-header-text " data-id="text">
<div class="entry-content">
<h1 class="titoloheader">Benvenuti</h1>
</div>
</div>
</div>
</div>
</div>
</div>
jQuery
const pageTitles = {
"41": "Hello",
"44": "Goodbye",
"47": "Ciao",
"3": "Arriverderci",
"313": "Hey",
"316": " Bye",
"318": " This is silly",
"50": "The end"
};
const changeHeader = () => {
let id = [...document.body.classList] // all the classes of the body tag
.filter(classStr => classStr.startsWith("page-id")); // find the one that starts with page-id
if (id.length)[, , id] = id[0].split("-") // if found (an array) grab the last part after last -
if (id && Object.keys(pageTitles).includes(id)) { // do we find that ID in the list
$("h1.titoloheader").text(pageTitles[id]); // change the header
}
};
$(document).ready(changeHeader);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body class="home page-template-default page page-id-47 logged-in admin-bar no-customize-support ct-loading" data-link="type-1" data-forms="classic">
<div data-row="middle" data-columns="1">
<div class="ct-container">
<div data-column="middle">
<div data-items="">
<div class="ct-header-text " data-id="text">
<div class="entry-content">
<h1 class="titoloheader">Benvenuti</h1>
</div>
</div>
</div>
</div>
</div>
</div>
To change the text of the h1 element in your example when the page loads, you can use:
window.addEventListener('load', event => {
const h1Element = document.querySelector("#main-container .entry-content h1");
h1Element.innerText = 'New H1 Text';
});
If you don't make the change to the H1 in the window load event callback, the element you're targeting likely won't be available in the DOM when you try to access it with document.querySelector.
jQuery:
$('#main-container div[data-row="middle"] .entry-content h1').html('Your New Title');
Vanila JS:
var el = document.querySelector("#main-container div[data-row="middle"] .entry-content h1");
el.innerHTML= "Your New Title";
Sometimes text can be replaced using pure CSS
See the collection of answers here:
How can I replace text with CSS?
Cons:
Doesn't supported by all browsers, check your requirements and
browser compatibility list.
Old text will remain hidden, can be
problem for some screen reader.
Pros:
Sometimes you cannot inject your JavaScript directly.
Here is a simple example from W3 schools
<!DOCTYPE HTML>
<html>
<body>
<h1 id="myHeader">Hello World!</h1>
<button onclick="displayResult()">Change text</button>
<script>
function displayResult() {
document.getElementById("myHeader").innerHTML = "Have a nice day!";
}
</script>
</body>
</html>
If you notice, they add a unique id to the h1 tag. This way way you can access the tag directly.
https://www.w3schools.com/tags/att_id.asp
I'm stuck in a thing where I need to replace with some other text.
I have tried the following code.
var text = $("#nbspData").text().replace(' ','a');
$("#removedData").html(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="nbspData">this is me.</p>
<p id="removedData"></p>
But when I inspect the code the is not removed.
That happens because text() doesn't returns those encoded chars, it just returns the text you're seeing, e.g.: "this is me". So there is nothing to replace. Change text() to html():
var text = $("#nbspData").html().replace(' ','a');
var text = $("#nbspData").html().replace(' ','a');
$("#removedData").html(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="nbspData">this is me.</p>
<p id="removedData"></p>
Additional info: Use a regex replace if you want to replace all occurences of :
var text = $("#nbspData").html().replace(/\ /g,'a');
console.log(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="nbspData">this is me.</p>
This is a solution for HTML tag and   etc and you can remove and add conditions
based on your reuirement
convertHtmlToText(passHtmlBlock)
{
str = str.toString();
return str.replace(/<[^>]*(>|$)| ||»|«|>/g, 'replaceWithAnyText');
}
Its my first time posting here but i'm desperate for a solution. I'm sorry in advance if my question format is not proper. So basically what i'm struggling with is appending json data to paragraphs in my html. My API is okay, i checked with console.log the data is there, but every time i try to append the data, an error pops up in my console stating: Uncaught TypeError: Cannot read property 'Drivers' of undefined.
I've tried removing MRData from function but that didn't seem to do anything.
$.getJSON("http://ergast.com/api/f1/2016/drivers.json", function(MRData) {
console.log(MRData);
var drId = MRData.DriverTable.Drivers[0].driverId;
var permanentNum = MRData.DriverTable.Drivers[0].permanentNumber;
var kod = MRData.DriverTable.Drivers[0].code;
$('#p0').append(drId);
$('#p1').append(permanentNum);
$('#p2').append(kod);
})
<body>
<p id="p0"></p>
<p id="p1"></p>
<p id="p2"></p>
</body>
What I'm hoping to accomplish here is to get the strings from each of the variables and to append them to my paragraphs.
the problem is that you think that the result data is MRData but instead it is an object which holds MRData.
data = {
MRData: {...}
}
accessing to MRData will make your code to work.
$.getJSON("http://ergast.com/api/f1/2016/drivers.json", function(data) {
//data is an object which will have MRData inside.
var MRData = data.MRData;
var drId = MRData.DriverTable.Drivers[0].driverId;
var permanentNum = MRData.DriverTable.Drivers[0].permanentNumber;
var kod = MRData.DriverTable.Drivers[0].code;
$('#p0').append(drId);
$('#p1').append(permanentNum);
$('#p2').append(kod);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<p id="p0"></p>
<p id="p1"></p>
<p id="p2"></p>
</body>
you must use
var MRData =data.MRData;
console.log(data.MRData);
var drId = MRData.DriverTable.Drivers[0].driverId;
var permanentNum = MRData.DriverTable.Drivers[0].permanentNumber;
var kod = MRData.DriverTable.Drivers[0].code;
$('#p0').append(drId);
$('#p1').append(permanentNum);
$('#p2').append(kod);
})
your reciver data has field MRData and you use var MRData =data.MRData;
Inside the json file you have a variable mrData so your start should be
MRData.MRData.DriverTable.Drivers
if you have a look at your json file it says
{
MRData={}
}
adding MRData= MRData.MRData; should fix the problem. or you could simple modify the jsonfile content to {DriverTable:{// bla bla bla }}
$.getJSON("http://ergast.com/api/f1/2016/drivers.json", function(MRData) {
console.log(MRData);
MRData= MRData.MRData; // here is a simple workout
var drId = MRData.DriverTable.Drivers[0].driverId;
var permanentNum = MRData.DriverTable.Drivers[0].permanentNumber;
var kod = MRData.DriverTable.Drivers[0].code;
$('#p0').append(drId);
$('#p1').append(permanentNum);
$('#p2').append(kod);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<p id="p0"></p>
<p id="p1"></p>
<p id="p2"></p>
</body>
I want to print variables in the same paragraph but on different lines. I was using this:
<p id="demo1"></p><p id="demo2"></p><p id="demo3"></p>
<button type="button" onclick="myFunction()">Try It!</button>
<script>
function myFunction()
{
var lastname="Doe";
var age=30;
var job="carpenter";
document.getElementById("demo1").innerHTML=lastname;
document.getElementById("demo2").innerHTML=age;
document.getElementById("demo3").innerHTML=job;
}
</script>
but it prints each value in a new paragraph. I tried changing to classname instead but I'm doing something wrong. Help me please. TY.
<p class="demo1, demo2, demo3"></p>
<button type="button" onclick="myFunction()">Try It!</button>
<script>
function myFunction()
{
var lastname="Doe";
var age=30;
var job="carpenter";
document.getElementByClassName("demo1").innerHTML=lastname;
document.getElementByClassName("demo2").innerHTML=age;
document.getElementByClassName("demo3").innerHTML=job;
}
</script>
Also can you use
document.getElementById("demo1").innerHTML=lastname;
and more then one id and value at then end? Something like this?
document.getElementById("demo1,demo2,demo3").innerHTML=lastname,age,job;
How can you read that correctly, I know the above not valid, but what is the correct method to do it?
Ty
Jared Moore
<p id="demo1"></p>
<button type="button" onclick="myFunction()">Try It!</button>
<script>
function myFunction()
{
var lastname="Doe";
var age=30;
var job="carpenter";
var concat = lastname + '<br />' + age + '<br />' + job
document.getElementById("demo1").innerHTML=concat;
}
</script>
The reason that the three parts are in three different paragraphs is that you have three p elements. If you want all the values to be in the same paragraph, you should use an inline element, such as span. This is what it would look like:
<p><span id="demo1"></span><span id="demo2"></span><span id="demo3"></span></p>
By the way, using innerHTML is asking for someone to hack your site; if your real code looks anything like this:
element.innerHTML = userSuppliedData
then anyone can run whatever JavaScript they want on your page by passing this:
<script type="text/javascript">
alert('All your site are belong to us.');
</script>
This is known as cross-site scripting, XSS. Instead, do this:
element.appendChild(document.createTextNode(userSuppliedData))