change href link in plain javascript - javascript

I'm creating a new DOM element so I can later populate it with data:
var bubbleDOM = document.createElement('div');
bubbleDOM.setAttribute('class', 'selection_bubble');
document.body.appendChild(bubbleDOM);
I want to iterate over links in this newly created element to turn
addresses like "something.something" into "http://www.something.something".
I don't want jQuery, so I tried this without success:
var links = bubbleDOM.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].href = "http://www." + links[i].href.value;
}

Couple of things stand out.
links[i].href.value isn't valid. Just use links[i].href.
You should check to make sure the href actually has something in it.
Here is an example that works for me:
var links = bubbleDOM.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
if (!!links[i].href && links[i].href.length > 0) { // Check that there is an href
links[i].href = "http://www." + links[i].href;
}
}

links[i].href.value will always be an absolute URL, so if the attribute in HTML looks like
<a href="something.something">
then the value of links[i].href.value will be something like
"http://current.domain/something.something"
Try using getAttribute('href') instead.

use getters and setter to access/modify the attributes : getAttribute and setAttribue.
Here's a demo : http://jsfiddle.net/rF9qk/

Related

How to use querySelector to find all external links with a specific class

I want to find out all external links (links that are not pointing to the current domain) within a specific class (.post-inner) but I cannot find out how to do it.
I think it could be achieved with querySelector (I am not using jQuery).
This is the current code which doesn't work:
function linkopener(a) {
var c = document.links;
for (var i = 0; i < c.length; i++) {
if (c[i].hostname != window.location.hostname && c[i].protocol != 'tel:' && c[i].protocol != 'mailto:' && c[i].querySelector('.post-inner')) {
c[i].target = '_blank';
c[i].rel = 'noopener noreferrer';
c[i].title = '\u00f6ffnet in neuem Fenster - ' + c[i].title;
c[i].className += ' external-link'
}
}
};
If your internal links are relative (do not start with "http://yourdomain.com/...")
You can use the querySelector to find all tags that have a protocol specifier like this:
var aTags = document.body.querySelectorAll('.post-inner a[href*="://"]');
If the tag has a "href" attribute that contains "://" and is inside an element with class "post-inner" it will be found.
I think you can do something like this,
$(".post-inner>a[href^="http:"] ,.post-inner>a[href^="tel:"], ...")
Try to use
c[i].classList.contains('post-inner')
instead

How to find and change part of html in IE6 by javascript

I have webpage and I need to make some changes in this page. I am using IE6 in compatibility mode:
The part of html I need to change seems like this:
<SPAN title="Klepnutím otevřete"
class=attachment url="/Activities/Attachment/download.aspx"
userId="{4618A8F6-8B8F-E611-940B-005056834715}"
merchantId="{74F4AC81-FB14-DC11-BF2E-00145ED73B3E}"
attachmentType="5"
attachmentId="{1828327C-74A6-E611-940B-005056834715}">
<IMG border=0
src="/_forms/attachments/16_generic.gif"
align=absMiddle> Account.xml
</SPAN>
I would like to change the url to something else by javascript.
Is there some way how to do it? I know, that there are some fuctions like getelementbyId, but I can not use it, as this element does not have the ID. Also it seems, that I can not use xpath, as it is not supported in IE6.
Thanks for all replies!
You said you're getting this: Object doesn't support property or method 'getElementsByClassName'
That means the document doesn't have that method on it. Here's a good polyfill for that method in older IEs:
function getElementsByClassName(node, classname) {
var a = [];
var re = new RegExp('(^| )'+classname+'( |$)');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;
}
Once that function is declared, you can use it. Just remember that it's not a method on the document like it would be in older browsers.
var spans = var tabs = getElementsByClassName(document.body,'span');
for(var i = 0; i < spans.length; i++) {
var title = spans[i].getAttribute('title');
if(title === "Klepnutím otevřete") {
spans[i].setAttribute('url', 'this/is/your/custom/url.aspx')
}
}
Here, I used the title attribute to try and find the right span. I have no idea if this title is unique to just this span element, so you might need to validate that and select it differently if needed.
Simply use getElementsByTagName
var spans = document.getElementsByTagName('span');
for (var i = 0; i < spans.length; i++) {
// find an element with a certain class
if (spans[i].getAttribute('class') == 'attachment') {
// set new value
spans[i].setAttribute('url', 'some other url');
}
}
<SPAN title="Klepnutím otevřete"
class="attachment"
url="/Activities/Attachment/download.aspx"
userId="{4618A8F6-8B8F-E611-940B-005056834715}"
merchantId="{74F4AC81-FB14-DC11-BF2E-00145ED73B3E}"
attachmentType="5"
attachmentId="{1828327C-74A6-E611-940B-005056834715}">
<IMG border=0
src="/_forms/attachments/16_generic.gif"
align="absMiddle"/> Account.xml
</SPAN>

How do I add target=“_blank” to a link within a div with an specific class name?

I´m trying to add target=“_blank” to all the links within the divs with an specific class name. I know how to do it with an ID:
window.onload = function(){
var anchors = document.getElementById('link_other').getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
}
But i´m trying to replicate the same, using classes instead of IDS. Any ideas of a how to do this without jquery?.
Thanks in davanced!
You can use querySelectorAll() and include a CSS selector. So if your class name is link-other:
document.querySelectorAll('.link-other a')
.forEach(function(elem) {
elem.setAttribute('target', '_blank');
})
<div class="link-other">
Wikipedia
Google
</div>
Use querySelectorAll and loop just like you did.
var anchors = document.querySelectorAll(".link_other a");
Or you can use getElementsByClassName and nested loops.
var parents = document.getElementsByClassName(".link_other");
for (var i = 0; i < parents.length; i++) {
var anchors = parents[i].getElementsByTagName("a");
for (var j = 0; j < anchors.length; j++) {
anchors[j].setAttribute('target', '_blank');
}
}
You can use document.querySelectorAll() which takes a css expression:
var anchors = document.querySelectorAll('.my_class a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
Or (ab)using the array prototype:
[].forEach.call(document.querySelectorAll('.my_class a'), function(el) {
el.setAttribute('target', '_blank');
});
You should also consider using addEventListener instead of window.onload:
window.addEventListener('load', function() {
// ...
});
Or the more appropriate:
document.addEventListener('DOMContentLoaded', function() {
// ...
});
You can also use the old school <base> element which will can set defaults for all a tags:
var base_el = document.createElement('base');
base_el.setAttribute('target', '_blank');
document.head.appendChild(base_el);
To achieve your expected result use below option
var addList = document.querySelectorAll('.link_other a');
for(var i in addList){
addList[i].setAttribute('target', '_blank');
}
Codepen - http://codepen.io/nagasai/pen/QEEvPR
Hope it works

Access dynamic generated div id

I have some div ids that are generated dynamicly via php
<div id='a<?php echo $gid?>>
How can I access them in JavaScript? All these divs start with "A" followed by a number.
Is there some kind of search function
getElementById(a*)?
Thanks for any help
No generic JavaScript function for this (at least not something cross browser), but you can use the .getElementsByTagName and iterate the result:
var arrDivs = document.getElementsByTagName("div");
for (var i = 0; i < arrDivs.length; i++) {
var oDiv = arrDivs[i];
if (oDiv.id && oDiv.id.substr(0, 1) == "a") {
//found a matching div!
}
}
This is the most low level you can get so you won't have to worry about old browsers, new browsers or future browsers.
To wrap this into a neater function, you can have:
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
The usage example would be:
window.onload = function() {
var arrDivs = GetElementsStartingWith("div", "a");
for (var i = 0; i < arrDivs.length; i++) {
arrDivs[i].style.backgroundColor = "red";
}
};
Live test case.
In case you choose to use jQuery at some point (not worth for this thing alone) all the above code turns to single line:
$(document).ready(function() {
$('div[id^="a"]').css("background-color", "blue");
});
Updated fiddle, with jQuery.
No, you need a fixed id value for getElementById to work. However, there are other ways to search the DOM for elements (e.g. by CSS classes).
You can use querySelectorAll to get all divs that have an ID starting with a. Then check each one to see if it contains a number.
var aDivs = document.querySelectorAll('div[id^="a"]');
for(var index = 0, len = aDivs.length; index < len; index++){
var aDiv = aDivs[index];
if(aDiv.id.match(/a\d+/)){
// aDiv is a matching div
}
}​
DEMO: http://jsfiddle.net/NTICompass/VaTMe/2/
Well, I question myself why you would need to select/get an element, that has a random ID. I would assume, you want to do something with every div that has a random ID (like arranging or resizing them).
In that case -> give your elements a class like "myGeneratedDivs" with the random ID (if you need it for something).
And then select all with javascript
var filteredResults=document.querySelectorAll(".myGeneratedDivs").filter(function(elem){
....
return true;
});
or use jQuery/Zepto/YourWeaponOfChoice
var filteredResults=$(".myGeneratedDivs").filter(function(index){
var elem=this;
....
return true;
});
If you plan to use jQuery, you can use following jQuery selectors
div[id^="a"]
or
$('div[id^="id"]').each(function(){
// your stuff here
});
You will have to target the parent div and when someone click on child div inside a parent div then you can catch the child div.
<div id="target">
<div id="tag1" >tag1</div>
<div id="tag1" >tag2</div>
<div id="tag1" >tag3</div>
</div>
$("#target").on("click", "div", function() {
var showid = $(this).attr('id');
alert(showid)
});
getElementById() will return the exact element specified. There are many javascript frameworks including jQuery that allow much more powerful selection capabilities. eg:
Select an element by id: $("#theId")
Select a group of elements by class: $(".class")
Select subelements: $("ul a.action")
For your specific problem you could easily construct the appropriate selector.

Javascript - Link Name Changing with restrictions

I'm trying to change the name of a link, however, I have some restrictions. The link is placed in code that looks like this:
<li class='time'>
Review Time
<img alt="Styled" src="blah" />
</li>
Basically, I have a class name to work with. I'm not allowed to edit anything in these lines, and I only have a header/footer to write Javascript / CSS in. I'm trying to get Review Time to show up as Time Review, for example.
I know that I can hide it by using .time{ display: hide} in CSS, but I can't figure out a way to replace the text. The text is also a link, as shown. I've tried a variety of replace functions and such in JS, but I'm either doing it wrong, or it doesn't work.
Any help would be appreciated.
You could get the child elements of the li that has the class name you are looking for, and then change the innerHTML of the anchor tags that you find.
For example:
var elements = document.getElementsByClassName("time")[0].getElementsByTagName("a");
for(var i = 0, j = elements.length; i<j; i++){
elements[i].innerHTML = "Time Review";
}
Of course, this assumes that there is one element named "time" on the page. You would also need to be careful about checking for nulls.
Split the words on space, reverse the order, put back together.
var j = $('li.time > a');
var t = j.text();
var a = t.split(' ');
var r = a.reverse();
j.text(r.join(' '));
This could have some nasty consequences in a multilingual situation.
Old school JavaScript:
function replaceLinkText(className, newContents) {
var items = document.getElementsByTagName('LI');
for (var i=0; i<items.length; i++) {
if (items[i].className == className) {
var a = items[i].getElementsByTagName('A');
if (a[0]) a[0].innerHTML = newContents;
}
}
}
replaceLinkText("time", "Review Time");
Note that modern browsers support getElementsByClassName(), which could simplify things a bit.
You can traverse the DOM and modify the Text with the following JavaScript:
var li = document.getElementsByClassName('time');
for (var i = 0; i < li.length; i++) {
li[i].getElementsByTagName('a')[0].innerText = 'new text';
}
Demo: http://jsfiddle.net/KFA58/

Categories