Reputation: 693
I have the following html code:
<div class="someclass">
<ul>
<li><a title="someFile" href="somefolder/somefile.pdf">File Name</a>
<li><a title="someFile2" href="somefolder/somefile2.pdf">File 2</a>
</ul>
</div>
I would like the link to become:
<li><a title="someFile" href="somefolder/somefile.pdf" target="_blank">File Name</a>
<li><a title="someFile2" href="somefolder/somefile2.pdf" target="_blank">File 2</a>
Can this to be done with pure javascript, without jquery or other libraries?
I have done similar things with jquery using getElementByID, but here element has no id, all that it has is the class "someclass" and for various reasons, I don't want to change the html. What I am trying to do is just to insert small javascript on the bottom of the page which will be executed when the document is loaded using the:
window.onload="myFunction()";
Can this task be accomplished on the way that I want to do it?
Upvotes: 2
Views: 1629
Reputation: 92
Try this:
var prnt = document.querySelector('.someclass ul').childNodes;
for(var i=0;i<prnt.length;i++){
if(prnt[i].nodeType == 1){
prnt[i].firstChild.setAttribute('target','_blank');
}
}
Output:
<div class="someclass">
<ul>
<li><a title="someFile" href="somefolder/somefile.pdf" target="_blank">File Name</a>
<li><a title="someFile2" href="somefolder/somefile2.pdf" target="_blank">File 2</a>
</ul>
</div>
Upvotes: 1
Reputation: 6992
you just need to write
var matches = document.querySelectorAll('a');
for (var i = 0; i < matches.length; i++) {
matches[i].setAttribute('target', '_blank');
}
Upvotes: 4
Reputation: 5468
var links = document.querySelector('.someclass').getElementsByTagName('a');
Array.prototype.forEach.call(links, function(el) {
// set attribute
el.setAttribute('target','_blank');
});
See http://jsfiddle.net/sjmcpherso/krktmghd/ for working example
This answer is is IE9+ so yes you don't really need jQuery
Upvotes: 3
Reputation: 2523
Try this:
var pageLinks = document.getElementsByTagName("a");
for(var x in pageLinks) {
pageLinks[x].target = "_blank";
}
Upvotes: 2
Reputation: 1199
Have a look here.
http://www.w3schools.com/js/js_htmldom_nodes.asp
As indicated, this is what you can do with only Javascript
var para = document.createElement("p"); //create p element
var node = document.createTextNode("This is new."); //create text element
para.appendChild(node); //append text to p
var element = document.getElementById("div1");
element.appendChild(para); //append p to somewhere in your page
Upvotes: -2