Accessing inline CSS properties using getElementsByClassName - javascript

I have this piece of HTML code.
<div class="tagWrapper">
<i style="background-image: url(https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>
I need to get that url within the brackets. I tried using the getElementsByClassName() method but it didn't work. Since url is not a HTML element, I have no idea on how to take out the value. I can't use getElementById(), because I can't add an id to the HTML (it's not mine). It needs to work in Chrome and Firefox. Any suggestions?

You didn't add a jQuery tag, so here's a native solution (note that this likely won't work on older versions of IE, but you said it only has to work on Chrome and FF):
var origUrl = document.getElementsByClassName("tagWrapper")[0]
.children[0].style.backgroundImage;
var url = origUrl.substr(4, origUrl.length - 5);
Or
var url = origUrl.replace("url(", "").replace(")", "");
Here's a fiddle
EDIT
Answering your comment
document.getElementsByClassName("tagWrapper")
gets all elements with the class name tagWrapper. So to get the first one, you grab the zero index
document.getElementsByClassName("tagWrapper")[0]
Then you want the first child under there, and the backgroundImage property on this first child.
document.getElementsByClassName("tagWrapper")[0]
.children[0].style.backgroundImage;
From there it's a simple matter stripping the url( and ) from it
var url = origUrl.substr(4, origUrl.length - 5);
or
var url = origUrl.replace("url(", "").replace(")", "");

You can use querySelector():
Demo: http://jsfiddle.net/ThinkingStiff/gFy6R/
Script:
var url = document.querySelector( '.tagWrapper i' ).style.backgroundImage;
url = url.substr(4, url.length - 5);

If you where using jquery you could do something like this
$(".tagWrapper i").css("background-image")

I think if you use jQuery it will be easer.
var w = document.getElementsByClassName('tagWrapper')[0];
for (var i=0; i<w.childNodes.length; i++)
if (w.childNodes[i].tagName && w.childNodes[i].tagName.toLowerCase() == 'i')
return w.childNodes[i].style.backgroundImage;

<div class="tagWrapper">
<i id="something" style="background-image: url(https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>
// script / without jQuery
var url = document.getElementById('something').style.backgroundImage.match(/\((.*?)\)/)[1];

Use jQuery!!!
$("div.tagWrapper i").css("background-image").substr(4, $("div.tagWrapper i").css("background-image").length-5)
Example

If You don't have to care about Microsoft browsers, the raw JavaScript is quite easy. You can use getElementsByClassName and getElementsByTagName, however it is easier to try querySelectorAll. I've included both. The use of regular expression preserve relative links.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type='text/javascript'>
var do_find_a = function() {
var tmp = document.getElementsByClassName('tagWrapper')[0];
var tst = tmp.getElementsByTagName('i')[0].getAttribute('style');
return do_alert(tst);
}
var do_find_b = function() {
var tst = document.querySelectorAll('.tagWrapper i')[0].getAttribute('style');
return do_alert(tst);
}
var do_alert = function(tst) {
var reg = /background-image:\s*url\(["']?([^'"]*)["']?\);?/
var ret = reg.exec(tst);
alert (ret[1]);
return;
}
document.addEventListener('DOMContentLoaded',do_find_a,false);
document.addEventListener('DOMContentLoaded',do_find_b,false);
</script>
</head>
<body>
<div class='tagWrapper'>
<i style='background-image: url("http://example.com/image.jpg");'></i>
</div>
Text to ignore.
</body>
</html>
And jsFiddle version:
http://jsfiddle.net/hpgmr/

Related

Removing first string character with substr in WordPress

I am trying to remove the "|" from the file size span tag. The syntax of my javascript code so far does look fine, but it's not working quite yet.
From my understanding I am using the proper syntax for substr: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
In Chrome, I am getting this console error:
Uncaught TypeError: Cannot read property 'substr' of undefined
In Firefox, I am getting this console error:
Uncaught TypeError: innerTextString is undefined.
Also the "|" isn't being removed as intended. Any ideas where I am going wrong here?
Thank you in advance.
<script>
const prettyLinkRightFileSize = document.querySelectorAll('.prettyFileList .float_right:nth-child(1)');
const innerTextString = prettyLinkRightFileSize.innerText;
innerTextString.substr(0);
</script>
.prettyFileList .float_right {
float: right;
}
<div class="prettyFileList">
<div>
<a href="#" class="prettylink">
<span class="float_right">| Size 150 KB</span>
<span class="float_right">28th Jan 2021</span>
</a>
</div>
</div>
You do not crop anything, when you use innerTextString.substr(0), as it has the same amount of characters like the original String.
var e = "ThisisaText";
var t = e.substring(0);
Log.v("e", e);
Log.v("t", t);
Output:
"ThisisaText"
"ThisisaText"
additionally you select the Items via classname. So I recommend, you crop all Items with the same class to provide consistency.
Try this code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="prettyFileList">| Testsize</div>
</body>
<script>
var c = document.getElementsByClassName('prettyFileList');
for (var i = 0; i < c.length; ++i) {
var item = c[i];
item.innerHTML = item.innerHTML.substr(1);
}
</script>
</html>
querySelectorAll() returns a static (not live) NodeList. You need to use prettyLinkRightFileSize[0].innerText.
const prettyLinkRightFileSize = document.querySelectorAll('.prettyFileList .float_right:nth-child(1)');
const innerTextString = prettyLinkRightFileSize.innerText;
To
const prettyLinkRightFileSize = document.querySelector('.prettyFileList .float_right:nth-child(1)');`
let innerTextString = prettyLinkRightFileSize.innerText;
innerTextString = innerTextString.slice(1);
console.log(innerTextString)
This will do the job:
<script>
Array.from(document.querySelectorAll('.prettyFileList .float_right:first-child'))
.map(element => element.innerText = element.innerText.substring(1));
</script>
It also works with multiple elements on your page!
If you do querySelectorAll you will get a nodeList with all elements matching the select statement. You have to iterate over these results to manipulate each of them (also if you only match one element: An array with one element still requires other treatment than the element it self).

Change href of <a> element using javascript

Please, code to change domain in href (html, JavaScript).
Exemple:
<a id="NewL" href="http://exemple.com/indice.html">Indice</a>
To:
<a id="NewL" href="http://exemple.net/indice.html">Indice</a>
Exemple code not working:
<script type = "text/javascript" >
function replace() {
var aEls = document.getElementById('NewL').getElementsByTagName('a');
aEls.href = aEls.href.replace('http://exemple\.com', 'http://exemple\.net');
}
</script>
Thanks, #t.niese:
<a id="NewL" href="http://exemple.com/indice.html">Indice</a>
<script type="text/javascript" >
function replace() {
var aEl = document.getElementById('NewL');
aEl.href = aEl.href.replace('http://exemple.com', 'http://exemple.net');
}
replace();
</script>
Please help me, not change in various ID in same page:
<a id="NewL" href="http://exemple.com/indice.html">Indice</a>
<a id="NewL" href="http://exemple.com/indice2.html">Indice 2</a>
<script type="text/javascript" >
function replace() {
var aEl = document.getElementById('NewL');
aEl.href = aEl.href.replace('http://exemple.com', 'http://exemple.net');
}
replace();
</script>
Element.getElementsByTagName():
[...]The subtree underneath the specified element is searched, excluding the element itself.[...]
so you search for the elements with the tag name a within your element with the id NewL
Because document.getElementById('NewL') is already your a element, you won't need the getElementsByTagName('a'), as of that you should only write:
var aEl = document.getElementById('NewL');
Also your replace is wrong, you don't need to escape the . if you pass the search as string.
aEl.href = aEl.href.replace('htp://exemple.com', 'htp://exemple.net');
Beside that Element.getElementsByTagName() returns a list of elements, so even if your search would have been correct, you would need to use a loop to iterate through that result.
change your javascript to the following:
<script type = "text/javascript" >
function replace() {
var aEl = document.getElementById('NewL');
aEl.href = aEl.href.replace('htp://exemple\.com', 'htp://exemple\.net');
}
</script>
You already selected the element by the getElementById no need to find the a class in it. Also you mispelled the variable which I changed to aEl

Get class from <body> tag within HTML string

I have a string of HTML like this
var html = "<html><head></head><body class='getMe'></body></html>";
I want to get the body tags class and I tried doing that like this.
$(html).filter("body").attr("class")
$(html).find("body").attr("class");
But both methods return undefined. Any help?
You do not need to parse into html, rather try RegExp:
var html = "<html><head></head><body class='getMe'></body></html>";
var clazz = html.match(/body\sclass=['|"]([^'|"]*)['|"]/)[1]; //getMe
Here, String.match() gives array of string for given pattern.
body\sclass=['|"]([^'|"]*)['|"] gives ["body class='getMe'", "getMe"]. Using (), you can grab a particular group.
Also works with multiple classes and other attributes:
var html = "<html><head></head><body class='getMe hey there' id='xyz' bgcolor='red'></body></html>";
var clazz = html.match(/body\sclass=['|"]([^'|"]*)['|"]/)[1]; //getMe hey there
Edited
In order to get classes belonging to body tag starting with header-:
var html = "<html><head></head><body class='getMe header header-1 header-two test'></body></html>";
var headers = html.match(/body\sclass=['|"]([^'|"]*)['|"]/)[1].match(/(header\-\w+)/g);
//["header-1", "header-two"]
Try
var html = "<html><head></head><body class='getMe'></body></html>";
var className = $("<html />", {"html":html}).find("body")[0].className;
console.log(className);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
Did you try to put it in a Variable? find the tag without ""
var MyClass = $(body).attr("class");
// or $(html).find(body).attr("class");

JS works in IE, Safari, Chrome but not in Firefox?

Most my work is done running on Webkit stuff and using Chrome's dev tools. But this code doesn't run in Firefox; it doesn't even throw a console error so I have no idea what's wrong. Any ideas. I'm sure its terribly easy. My code is designed to look throw a div for a specific syntax "t_" "r_" which are references to an external document; I'm trying to find all said references and replace them with hyperlink. I"m a novice JS coder so sorry for the naiveness you'll undoubtedly see in here.
(I'm using FF 22.0)
<!DOCTYPE html>
<html>
<head>
<script>
function pre_forwarder(){ //First Step
patt_1=/\[r_/g;
patt_2=/\[t_/g;
patt_S_and_R_1 = "[r_";
patt_S_and_R_2 = "[t_";
forwarder(patt_1,patt_S_and_R_1);
forwarder(patt_2,patt_S_and_R_2);
}
function forwarder(Pattern,Pre_SearchReplace){
rule_string = document.getElementById("divid");
rule_string = rule_string.innerText;
var patt1 = Pattern;
while (patt1.test(rule_string)==true)
{
begin_string = patt1.lastIndex;
fullpar_string = patt1.lastIndex + 5;
partial_string = rule_string.slice(begin_string,fullpar_string); //5 characters
//alert("partial_string-"+partial_string);
refined_string_end = partial_string.indexOf("]");
refined_str = partial_string.slice(0,refined_string_end); //raw number
full_str = Pre_SearchReplace+refined_str+"]"; //restructured
SectionNum = refined_str;
SearchReplace = full_str; //Variable to pass to parse()
//alert("S&R="+SearchReplace+" >> full_string-"+full_str);
//alert("S&R"+SearchReplace+">>SecNum-"+SectionNum+">>Pre-Search-"+Pre_SearchReplace);
Parse(SearchReplace,SectionNum,Pre_SearchReplace);
}
//var patt_end=/\[t_/g;
}
function Parse(SearchReplace,SectionNum,Pre_SearchReplace){
if (Pre_SearchReplace == patt_S_and_R_1){
ref_URL = "UEB_Ref.html#";
}else if (Pre_SearchReplace == patt_S_and_R_2){
ref_URL = "UEB_Tech.html#";
}
linkCreate = 'Link to ch-'+SectionNum+' ';
document.getElementById("divid").innerHTML = document.getElementById("divid").innerHTML.replace(SearchReplace, linkCreate);
}
function Dude(SectionNum){
alert(SectionNum);
}
</script>
</head>
<body onload="pre_forwarder();">
<button onclick="pre_forwarder();">
New Tool</button>
<div id="divid">
hello [dude] ok the end [r_12.1][r_7] [r_22]
<br>bro try this [t_15.3][t_6] [t_5.5]
</div>
<div id="hyperlink">
</div>
</body>
</html>
You've rule_string = rule_string.innerText; at line 15. FF doesn't know innerText, you need to use textContent, or a fix like:
rule_string = rule_string.innerText || rule_string.textContent;
A live demo at jsFiddle.
As a side note: Looks like your app is based on global variables. Please don't use this kind of programming technique. It'll do the job, as long as there's not much of code, but when your apps are getting larger, you'll lose control over a ton of global variables.
For starters, you can read JavaScript Guide at MDN, especially chapters 4, 8 and 9.

Adding javascript variable to hyperlink within script

I have been trying to create a hyperlink using a variable defined earlier in the same function to append:
var NAMEVARIABLE = responseArray[i].Name;
var TITLE_Game = document.createElement("p");
TITLE_Game.className = "TITLE_Game";
TITLE_Game.innerHTML = "<a href='Game_NAMEVARIABLE.html'>Games</a>";
I have tried the following using the solution found here: Passing Javascript variable to <a href >
Games
But that didn't work. I then tried adding an ID:
<a id="link" href="Game_.html?propid=">Games</a>
And adding this to the script: document.links["link"].href += NAMEVARIABLE;
This didn't work either. These links are occuring within Isotope, which I've run into newbie-problems making sure my JSON data is loading before the script executes. That's all working now, but I'm not sure if the reason the above methods aren't working is because of a similar issue, or if they simply are not the proper way to go about this.
Any help is much appreciated. Thank you
first of all, try debug your variable :
var NAMEVARIABLE = responseArray[i].Name;
alert(NAMEVARIABLE);
is it returning the desired return value or not.
and then the second thing, in your first style of script, try this instead :
TITLE_Game.innerHTML = "<a href='Game_"+NAMEVARIABLE+".html'>Games</a>";
I assumed you have (static) html collection with game_[number_id].html format
and if it's so, you can try further with your second style of script, and change it to this :
Games
you need to learn further about javascript strings concatenation
Use string concatenation to build up your inner html string.
Example:
var nameVariable = 'Foo';
var innerHtmlText = nameVariable + 'bar';
$('#someElement').html(innerHtmlText);
The contents of someElement will then contain the text: 'Foobar';
You just need string concatenation. modify link's href onclick would be considered as spam in most modern browser.
<div id="result">
the result:
</div>
<script type="text/javascript">
var name = "foo_bar";
var url = "page.html?key=" + name; //or.. "page_" + name + ".html";
var link = 'link here';
$("#result").addClass("g_title");
$("#result").append(link);
</script>
This can be achieved by either (i.e. pure JS or jQuery) ways without much hassle. Suppose you have this <a> element with some href
<a id="Link" href="/collection/categories/">Games</a>
Pure JavaScript way:
window.onload = function() {
var link= document.getElementById('Link'),
url = link.href + responseArray[i].Name + '.html';
link.setAttribute('href', url);
}
Using Jquery:
$(function(){
var link= $('#Link'),
url = link.attr('href') + responseArray[i].Name + '.html';
link.attr('href', url);
});

Categories

Resources