I want to load an iframe using just javascript, so far I've been using this:
$(".punctis-social-box").html("<iframe></iframe>");
But since it is the only instruction I have that uses jQuery, I'll like not to depend any more on jQuery.
Maybe not the best way to start:
var elements = document.getElementsByClassName("punctis-social-box");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "<iframe></iframe>";
}
Or using querySelectorAll:
var elements = document.querySelectorAll(".punctis-social-box");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "<iframe></iframe>";
}
In order to avoid all bad practicesTM you may use document.createElement instead of explicit change of inner HTML:
var element = document.querySelector(".punctis-social-box"),
iframe = document.createElement("iframe");
while (element.firstChild) { // the fastest way
element.removeChild(element.firstChild); // to clear the contents
}
element.appendChild(iframe); // adding new <iframe>
Method 1:
var social_boxes = document.getElementsByClassName('punctis-social-box');
social_boxes[0].innerHTML += '<iframe></iframe>'; // add to first element, loop thru "social_boxes" if you want to add iframe to all elements
Method 2 (better):
var social_boxes = document.getElementsByClassName('punctis-social-box');
var iframe = document.createElement('iframe');
social_boxes[0].appendChild(iframe); // add to first element, loop thru "social_boxes" if you want to add iframe to all elements
Related
So by using native javascript, how would I go about saying
"if this object has this css class, add this to the title attribute"
document.addEventListener("DOMContentLoaded", function(event) {
if(element.classlist.contains("current_page_item")||element.classlist.contains("current-page-ancestor")){
}
});
That is as far as I've gotten, I'm trying to stick to native javascript just so we don't have to load up any libraries and can keep the site as minimalist as possible.
You can use getElementsByClassName()
var x = document.getElementsByClassName("current_page_item");
Then loop and add title
x.forEach(function(element){
element.title = "title";
});
or
for (var i = 0; i < x.length; i++) {
x[i].title ="title";
}
To answer to your comment, to apply the title to the "a" element that is a child of the div element that has the "current_page_item" class
for (var i = 0; i < x.length; i++) {
var y = x[i].getElementsByTagName("a");
y[0].title = "title";
}
Similar to Rohit Shetty's reply, you could also use the querySelector:
let elements = document.querySelector(".current_page_item");
elements.forEach(function(e) {
e.title = "title";
);
You can use getElementsByClassName()
var x = document.getElementsByClassName("current_page_item");
for(var i=0;i<x.length;i++){
x[i].title += "BLAH";
}
I don't now if I have understood well.
But let's try.
First, locate the elements.
const nodes = document.querySelectorAll('.current_page_item, .current_page_item')
// nodes are the elements of one of the classes names
Then, apply the class Names to title.
function containsOfTheClasses (node) {
return classNames.some(x => node.classList.contains(x))
}
nodes.forEach(function (node) {
node.title += classNames.filter(containsOfTheClasses).join(' ')
})
I'm trying to write a javascript what is searching for all of the links on the page, then it is adding them to the bottom, under the original content.
"Document.links" seems to do the finding part, it is also listing them, but they are not clickable. So I tried to add some html codes (startHref and endHref lines), which broke the whole thing of course.
My (non-working) script:
var links = document.links;
for(var i = 0; i < links.length; i++) {
var preLink = document.createTextNode("LINK: ");
var linkHref = document.createTextNode(links[i].href);
var lineBreak = document.createElement("br");
var startHref = document.createElement("a href="");
var endHref = document.createElement(""");
document.body.appendChild(preLink);
document.body.appendChild(startHref);
document.body.appendChild(linkHref);
document.body.appendChild(endHref);
document.body.appendChild(lineBreak);
}
If this will work I'd also like to have them listed with a number in front of each line (starting with 1 - could be set in the preLink part) - if not too hard to implement.
Also, is there a way to list not all of the links, but only those matching with something? Like only links with a specific domain. Thank you!
As you have already found out, you can get all links in a document with:
var links = document.links;
Now you have an HTMLCollection. You can iterate through it and display all links. For better layout you can put them in a paragraph (p). This would be the loop:
for (var i = 0; i < links.length; i++) {
var p = document.createElement("p");
p.appendChild(links[i]);
document.body.appendChild(p);
}
Now all links are appended at the end of the page, every link is on its own line and they are clickable. Please try this out.
EDIT: as of your comment, if I understand it right, you have just to put one additional line:
for (var i = 0; i < links.length; i++) {
var p = document.createElement("p");
// the following line is added
links[i].innerHTML = links[i].href;
p.appendChild(links[i]);
document.body.appendChild(p);
}
That line will simply replace the inner HTML of the link with its value for the attribute href.
EDIT:
The variable links just points to document.links. The existing links are therefore removed from their original position and appended to the end. If you try to create new links in the for loop, like document.createElement("a") you will create an endless loop, because you're iterating through all links in the document. You remember, the variable links is not a snapshot of document.links when created, but points to it.
You can work around this with creating an array:
var links = [];
// populate the array links
for (var j = 0; j < document.links.length; j++) {
links.push(document.links[j].cloneNode());
}
Now this is a snapshot of all links on the page. Every links is cloned and pushed to the array. Now run the for loop and the original links aren't removed.
If the original link was something like:
This is an example.
it will become:
http://example.com
But if you want just:
http://example.com
then you have to adapt the code:
for (var i = 0; i < links.length; i++) {
var p = document.createElement("p");
var a = document.createElement("a");
a.href = links[i].href;
a.text = links[i].href; // you can use text instead of innerHTML
p.appendChild(a);
document.body.appendChild(p);
}
If you want to style the output you can add classes like this:
p.classList.add("my-css-class");
I hope this helps you to achieve your goal.
I am trying to write a chrome extension to change all hrefs in a page using this code
var a = document.querySelector("a[href]");
a.href = "http://www.google.com";
But this code only fetches the first href but only if it is not embedded in another attribute(If the term is wrong I am meaning div, p, h etc.)
Could someone show me how to fetch all hrefs no matter what?
document.querySelector only returns the first element within the document, and so in this case you will want to use document.querySelectorAll which instead returns a list of all matching elements.
var elements = document.querySelectorAll('a');
for (var i = 0; i < elements.length; i++) {
elements[i].href = 'http://google.com';
}
but only if it is not embedded in another attribute(If the term is wrong I am meaning div, p, h etc.)
I believe you are talking about tags instead of attributes. To select all tags with the present of the href attribute, do this:
var list = document.querySelectorAll("*[href]");
for(var i = 0; i < list.length; i++){
list[i].href = "http://www.google.com";
}
If there are a bunch of H1 and P tags in my document and there is no ID associated with them, how do I target particular P and H1 tags using JavaScript? I have no control over the creation of the page; thus, I'm resorting to using JavaScript to manipulate on the client side.
This sounds like a sad place to be, but if you've no access, you'll want to use something like:
var pTags = document.getElementsByTagName('p');
for (var i = pTags.length; i--;) {
var self = pTags[i];
self.style.display = 'none';
}
This however will hide all of them, so you'll want to filter out the ones you do have. And the same for your H1 tags. Not an ideal solution as you'll likely run into further issues.
You mention that some do not have ID attributes, you could filter those out:
var pTags = document.getElementsByTagName('p');
for (var i = pTags.length; i--;) {
var self = pTags[i];
if (!self.hasAttribute('id')) {
self.style.display = 'none';
}
}
var ps = document.getElementsByTagName('p');
for (var i = 0, l = ps.length; i < l; i++) {
ps[i].setAttribute('style', 'display: none');
}
Repeat for h1 tags.
By Order
By Value
By constellation (So you know there is a img bevor the h1 or something else)
I'm writing a javascript function where I get a ul object from my HTML and want to set the text of one of the li elements in theul`. I'm doing:
list = document.getElementById('list_name');
Then I want to access the ith li element of list using a loop.
I have:
for (i = 0; i < 5; i++) {
list[i].innerHTML = "<a>text</a>";
}
but this is not working. What is the proper way to do it?
You need to access the child li elements of the ul. JavaScript and the DOM API can't automagically do that for you.
var list = document.getElementById('list_name'),
items = list.childNodes;
for (var i = 0, length = childNodes.length; i < length; i++)
{
if (items[i].nodeType != 1) {
continue;
}
items[i].innerHTML = "<a>text</a>";
}
You could also use getElementsByTagName('li') but it will get all descendent li elements, and it seems you want only the direct descendants.
You could also avoid innerHTML if you want.
var a = document.createElement('a'),
text = document.createTextNode('text');
a.appendChild(text);
items[i].appendChild(a);
innerHTML can cause issues, such as lost event handlers and the performance issue of serialising and re-parsing the HTML structure. This should be negligible in your example, however.
jQuery Sample code, although the others work:
$("#list_name li").text("<a href=''>text</a>");
Its much more succinct with jQuery
You can try the following
var el = document.createElement("li"),
content = document.createTextNode("My sample text"),
myUl = document.getElementById("ulOne");
el.appendChild(content);
el.id = "bar";
myUl.appendChild(el);
Here's the demo: http://jsfiddle.net/x32j00h5/
I prefer a aproach using getElemenetByTagName, if somehow you get a extra node like a script tag or a span you will have problems. A guess this code will help you:
var list = document.getElementById("mylist");
var items = list.getElementsByTagName("li");
for(var i = 0, size = items.length; i< size; i++){
items[i].innerHTML = "<a href='#'>LINK</a>";
}