user2417624
user2417624

Reputation: 693

how can I add an html to an element without id with javascript without jquery

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

Answers (5)

SSS
SSS

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>

Working Demo

Upvotes: 1

Shailendra Sharma
Shailendra Sharma

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');
}

Fiddle

Upvotes: 4

sjm
sjm

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

Bardo
Bardo

Reputation: 2523

Try this:

var pageLinks = document.getElementsByTagName("a");
for(var x in pageLinks) {
    pageLinks[x].target = "_blank";
}

Upvotes: 2

Tree Nguyen
Tree Nguyen

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

Related Questions