Change href of <a> element using javascript - 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

Related

Using a variable as the href

I want to have the href consist of a variable set in javascript, I also need the text that is displayed on the page to be a variable. In the example below I would like to have the string "http://google.com" be assigned to a variable, I also need to have "My Link Name" as a variable. I have looked at similar questions here but I don't see what addresses this particular situation.
Go Here Now<br>
In the example below I can create a variable called myLinkName and set it to the string "Go here now" however I don't know how to create a variable and set it to the value of the href e.g. "http://google.com"
<script type="text/javascript">
var myLinkName = "Go Here Now";
</script>
<a href="http://google.com">
<script type="text/javascript">
document.write(myLinkName)
</script></a>
You have to use the DOM API
HTML
<a id="aLink"></a>
Javascript
let link = document.getElementById('aLink');
link.href = "https://google.com";
link.innerText = 'This is my Link'
The complete code:
<html>
<body>
<a id="aLink"></a>
<script>
let link = document.getElementById('aLink');
link.href = "https://google.com";
link.innerText = 'This is Link';
</script>
</body>
</html>
I fear you are using some very old JavaScript material.
The usage of document.write() is depricated.
The approach you are following is antiqated. Today JS is not evaluated and just written to the document. Instead the document is explicitly manipulated.
First of all: <script> is sufficient to declare some JavaScript. The type attribute is not needed anymore.
<a id=myLink></a>
<script>
//get a reference to the a element
const myLink = document.getElementById("myLink");
//set the text
myLink.innerText = "Click me!";
//set href
myLink.href = "http://google.com";
</script>
You can set href attribute like this
var text = 'Go Here Now';
var href = 'http://google.com'
var atag = document.getElementsByTagName('a')[0];
atag.innerText = text;
atag.href = href;
var text = 'Go Here Now';
var href = 'http://google.com'
var atag = document.getElementsByTagName('a')[0];
atag.innerText = text;
atag.href = href;
<br>
I would create an object that contains your link name and href and on page load, assign accordingly. Something like:
window.addEventListener('load', function(){
var link = {
name : 'My Link Name',
href : 'http://google.com' //should use : instead of =
};
var myLink = document.getElementByTagName('a')[0]; //You would change this to whatever selector you want.
myLink.innerText(link.name);
myLink.setAttribute('href', link.href);
}, true);
Syntax may not be perfect. And, depending on your situation, it may be better to accomplish this with your server side code. Hope this helps!
You can change the href attribute by doing this:
<a href="http://google.com" id="link">
<script type="text/javascript">
var yourtext = 'Go Here Now';
var href = 'http://google.com';
document.getElementById('link').href = myLinkName;
document.getElementById('link').innerText = yourtext;
</script></a>
By using JQuery we can update/add href to the element like below.
HTML code:
Click Here
JQuery code:
$("#linkId").attr("href", "http://www.google.com/'");

Extract element by ID from string?

I have a string which contains this text:
<!DOCTYPE html>
<html>
<head>
<title>ExtractDiv test</title>
</head>
<body>
<p>Apples and oranges</p>
<div id="main">
<ul style="list-style-type: upper-roman">
<li>Äpfel</li>
<li>Birnen</li>
</ul>
</div>
<p>Men and women</p>
</body>
</html>
Now I need a JavaScript function which gives me back a DOM element with a specific ID as a string from this text, for example:
function ExtractElementByIdFromString(HTMLString, IdString)
{
var ExtractedElement = ???(HTMLString, IdString);
return ExtractedElement;
}
So the RESULT of this function in this case would be:
<div id="main">
<ul style="list-style-type: upper-roman">
<li>Äpfel</li>
<li>Birnen</li>
</ul>
</div>
Is this possible?
You can parse an HTML string with the native DOMParser:
var str = "<!DOCTYPE……………" // your HTML string
var doc = new DOMParser().parseFromString(str, "text/html")
Then just use regular DOM methods:
console.log( doc.getElementById("main") )
Note that using a DOMParser is more efficient and safer than inserting the string somewhere in your document's innerHTML, because only the structure will be created — <script> elements won't be executed, images won't be loaded, CSS will no try to apply to it, no rendering will occur, etc.
You can create a temporary element, put the HTMLString as a content to it, then use querySelector to get an element with passed id. Something like this:
function ExtractElementByIdFromString(HTMLString, IdString) {
var result,
temp = document.createElement('div'); // Create a temporary element
temp.innerHTML = HTMLString; // Set the passed string as HTML to the temporary element
result = temp.querySelector('#' + IdString).outerHTML; // Find an element with the passed id
return result;
}
A working demo at jsFiddle.

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");

How to access JavaScript variable in HTML tags?

I am trying to access JavaScript variable in the href attribute of anchor tag.
JavaScript Function:
<script type="text/javascript">
function fun(ReqTextbox)
{
var queueData =document.getElementById(ResTextbox).value;
//some more code
}
</script>
HTML code:
<body>
<input type="text" value="<%=dynamicValue%>" id="<%=dynamicId%>"/>
<a href="servlet?variablename="<%Eval(queueData)%>" onclick=fun('<%=dynamicvalue%>');>LINK</a>
</body>
I know that I am going to wrong at variablename="<%Eval(queueData)%>".
Can someone please help me how to access and pass JavaScript variable as a query string parameter?
First, I think you made a typo :
function fun(ReqTextbox) {
var queueData = document.getElementById(ResTextbox).value;
//some more code
}
You get ReqTextbox parameter but you use ResTextbox. Then, since Javascript is client-sided, you have to manually update the href tag using href attribute. So your function would be like :
function fun(ReqTextbox) {
var queueData = document.getElementById(ReqTextbox).value;
document.getElementById('myAnchor').href = "servlet?variablename=" + queueData;
//some more code
}
And give your anchor tag an id, myAnchor in my example.
Modify HTML code as given below -
<body>
<input type="text" value="<%=dynamicValue%>" id="<%=dynamicId%>"/>
<div id="example2">
<a href="servlet?variablename="<%Eval(queueData)%>" onclick=fun('<%=dynamicvalue%>');>LINK</a> </div>
</body>
Use this to pass query string -
$("#example2 a").attr("href", url + "?variablename=" + queueData);
If I understand you correctly inside fun() function try to use:
var queueData = this.getAttribute('id');
That way you will get id value when runnning onclick() function.

Accessing inline CSS properties using getElementsByClassName

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/

Categories

Resources