Is this possible? Or is there a way to tack on and ID to an existing div?
This is my code. I can't get the code to work using classes, but I found when I used getElementById and changed the div to an ID, that it did. But I have a ton of already posted stuff so it would take forever to go through all those posts and change it manually to an ID.
Can I incorperate JQuery in this and still have it work? I tried that with something I stumbled across but it didn't work so I removed it. I don't remember what it is now though. :S
<div id="imdb" class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnum = document.getElementsByClassName("imdb");
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnum + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
window.onload = imdbdiv();
</script>
Can anyone help. I cannot for the life of me figure this out.
JsFiddle
Your problem was, you were appending the collection returned by document.getElementsByClassName instead of looping through the elements in the collection. You can verify this by looking at the href property of the link in your jsFiddle. You must loop through the values, then access the data in their innerHTML property.
You can use document.querySelectorAll to get a list of all elements matching a certain CSS selector, in your case .imdb. This is more flexible, in case you want to select elements with more than one class. I've pasted the code from the updated jsFiddle below.
function imdbdiv() {
var imdbMain = "http://www.imdb.com/title/",
end = "/#overview-top",
imdbValueDivs = document.querySelectorAll('.imdb'),
length = imdbValueDivs.length,
// Iterator values
i,
newDiv,
newLink;
// Loop over all of your link value containers
for (i = 0; i < length; i++) {
// Create the container
newDiv = document.createElement('div');
// Create the new link
newLink = document.createElement('a');
newLink.href = imdbMain + imdbValueDivs[i].innerHTML + end;
newLink.innerHTML = "My favorite film";
// Add the link to the container,
// and add the container to the body
newDiv.appendChild(newLink);
document.body.appendChild(newDiv);
}
}
window.onload = imdbdiv();
If you have many such divs on your page, then it could be like this:
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnums = document.getElementsByClassName("imdb");
for (var i =0; i < idnums.length; i++) {
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnums[i].innerText + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
}
window.onload = imdbdiv();
</script>
See jsfiddle
UPDATE:
The following string was incorrect:
window.onload = imdbdiv;
Okay, so your question is a little bit unclear.
The way I understood your question is that you have a whole bunch of div elements with class attribute and what you want is to simply copy the class value to the id attribute of the div elements.
If that's correct then try something like this with jquery:
<script>
$(document).ready(function(){
$(".imdb").each(function(imdbDiv){
var classValue = imdbDiv.attr("class");
imdbDiv.attr("id", classValue);
});
});
</script>
Related
READ THE EDIT AT THE BOTTOM! :)
I am making a little website where the user can fill in multiple text boxes, and when they come back later, their text boxes come back. (Pretty much a terrible helpdesk system using localstorage).
I have three fields the user can fill out, then when the fields are submitted they should appear below, in a div. Currently i am only able to get the first field to be shown, as i append it to a static div, but i want to append the rest of the fields to the first one. This wouldnt be too hard, but i cant seem to append a child to a div that doesnt have a set ID (without somehow hardcoding it).
I have tried things like
divAId + i.appendChild(divB)
And
var divAIdNumber = divAId + i;
divAIdNumber.appendChild(divB);
, but nothing seems to work.
Here is the code in question:
gradStorages = JSON.parse(localStorage.getItem('gradStorages'));
var iFeil = 0;
function feilDivCreate(){
const divF = document.createElement("div");
divF.className = "feilDiv";
divF.id = "feilDivId" + iFeil;
listIdIncrement();
divF.appendChild(document.createTextNode(set1));
textContainer2.appendChild(divF);
iFeil += 1;
}
var iOffer = 0;
var feilIdNumber = "feilId";
function offerDivCreate(){
const divO = document.createElement("div");
divO.className = "offerDiv";
divO.id = "offerDivId" + iOffer;
listIdIncrement();
divO.appendChild(document.createTextNode(set1));
feilIdNumber + iOffer.appendChild(divO);
iOffer += 1;
console.log(feilIdNumber + "TATATATAT");
}
var set1 = "set1 Not Defined";
var set2 = "set2 Not Defined";
var set3 = "set3 Not Defined";
function extract(){
for(let i = 0; i < feilStorages.length; i++){
set1 = feilStorages[i];
set2 = offerStorages[i];
set3 = gradStorages[i];
feilDivCreate();
offerDivCreate();
gradDivCreate(); // same as offerDiv
}
}
(can add more, or make a jsfiddle if needed.)
I need a way to append offerDiv to feilDiv, but its not so simple because feilDiv's id is feilDivId + i where i goes up by one for each new feildiv added.
Any tips for how i can achieve this?
EDIT: Here is a simplified version, showing all the code necessary to understand what im trying to do. https://codepen.io/kossi1337/pen/xxKPRvv
Might be easier to just make a new question with all the new code, but im not too sure if that allowed.. Let me know if i have to change anything about my question :)
In this code:
var divAIdNumber = divAId + i;
divAIdNumber.appendChild(divB);
It seems like you are trying to append an element to the Integer value you just created by adding i to some number. You need to grab the parent node, either via document.querySelector or using jQuery, then append to the parent. The browser has no idea what to do when you try to append markup to a number. It expects a DOM location that it will be appended to.
It should be like this:
var divAIdNumber = divAId + i;
var html = "<div class='" + divAIdNumber + "'> Content here </div>";
var element = document.querySelector(".my-element");
element.appendChild(html);
I have such code:
var pageCount = 5; //for example, doesn't really matter
var paginationList = document.createElement("ul");
paginationList.className = "pagination";
for(var i = 1; i <= pageCount; i++){
var paginationNode = document.createElement("li");
var paginationLink = document.createElement("a");
paginationLink.innerHTML = i;
paginationLink.href = "#";
paginationLink.onclick = function(){ console.log("yay"); }; //removed loadProperties here
paginationNode.appendChild(paginationLink);
paginationList.appendChild(paginationNode);
}
divxml.innerHTML = "";
divxml.appendChild(paginationList);
//code replaced by this comment inserts a lot of content to divxml
//for this bug or something to work, you need next line
divxml.innerHTML += "<br>";
divxml.appendChild(paginationList);
As you can see, I'm doing pagination here. The problem is that first pagination buttons don't work, I can't see yay in console when I click on them, but the second and last ones do work (I see yay in console when I click on them). What's wrong, How do I fix that?
You will have to create two list elements and two sets of list item elements for this to work:
var pageCount = 5; //for example, doesn't really matter
var paginationList1 = document.createElement("ul");
var paginationList2 = document.createElement("ul");
paginationList1.className = paginationList2.className = "pagination";
for(var i = 1; i <= pageCount; i++){
paginationList1.appendChild(createPaginationLink(i));
paginationList2.appendChild(createPaginationLink(i));
}
document.body.appendChild(paginationList1);
document.body.appendChild(document.createElement("br"));
document.body.appendChild(paginationList2);
function createPaginationLink(text) {
var paginationNode = document.createElement("li");
var paginationLink = document.createElement("a");
paginationLink.innerText = text;
paginationLink.href = "#";
paginationLink.addEventListener("click", function(){ console.log("yay"); }); //removed loadProperties here
paginationNode.appendChild(paginationLink);
return paginationNode;
}
And as stated in the other answer, mutating innerHTML will cause your elements to be re-created without their event listeners, so instead create and append your <br/> element using createElement and appendChild.
Codepen
divxml.innerHTML += "<br>";
Reading from innerHTML converts the DOM into HTML. The HTML does not have the event handlers that were attached to the DOM.
Writing the HTML back to the innerHTML (after appending <br> to it) converts the HTML to DOM and overwrites the DOM that was there before.
You have now destroyed the event handlers.
Don't use innerHTML.
I am working on a web application in which I have to fill user friend list using JavaScript. I used the following code to perform that, but I don't get any name inside it and only div are created I need to create heading also. How to add heading using javascript and fill value in it?
$(document).ready(function(){
var name = ["Amar", "rahul", "vinay"];
var hobby=["aaa","bbb","ccc"];
var toAdd = document.createDocumentFragment();
for(var i=0; i <name.length; i++){
var newDiv = document.createElement("div");
var newheading = document.createElement("h2");
newDiv.id='r'+i;
newDiv.id='h'+i;
newDiv.innerHTML = name[i];
newDiv.className = 'ansbox';
toAdd.appendChild(newDiv);
}
document.getElementById('sel').appendChild(toAdd);
Please try this code
$(document).ready(function(){
var name = ["Amar", "rahul", "vinay"];
var hobby=["aaa","bbb","ccc"];
var toAdd = document.createDocumentFragment();
for(var i=0; i <name.length; i++){
var newDiv = document.createElement("div");
var newheading = document.createElement("h2");
newheading.innerText = hobby[i];
newDiv.id='r'+i;
newDiv.id='h'+i;
newDiv.innerHTML = name[i];
newDiv.className = 'ansbox';
toAdd.appendChild(newheading);
toAdd.appendChild(newDiv);
}
document.getElementById('sel').appendChild(toAdd)
});
Fiddle
Hope this will help you.
Hope This Will Help. Add the heading element inside division
newDiv.appendChild(newheading);
Check Fiddle
If you want the div to appear in that order just reverse the order in which you write appendChild like adding "toAdd.appendChild(newDiv);" first and then adding "toAdd.appendChild(newheading);" later.
I need to change this bit of jQuery..
$(function() {
$("#breadcrump").append("<div id='oldsite'>Can't find what you're looking for? Try our old website: <a href='http://www.brooksbarn.co.uk'>Old Website (brooksbarn.co.uk)</a> or<a href='mailto:info#brooksbarn.co.uk?Subject=Brooksbarn.com Part Enquiry' target='_top'>E-Mail</a></div>");
});
Into regular javascript, I've looked into many ways, but my lack of js knowledge seems to be my stumbling block.
Here is what I've come up with so far:
document.body.onload = addElement;
function addElement () {
// create a new div element
// and give it some content
var newDiv = document.createElement("oldsite");
var newContent = document.createTextNode("Can't find what you're looking for? Try our old website: <a href='http://www.brooksbarn.co.uk'>Old Website (brooksbarn.co.uk)</a> or<a href='mailto:info#brooksbarn.co.uk?Subject=Brooksbarn.com Part Enquiry' target='_top'>E-Mail</a>");
newDiv.appendChild(newContent); //add the text node to the newly created div.
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("breadcrump");
document.body.insertBefore(newDiv, currentDiv);
}
Why do you don't do that :
document.getElementById("breadcrump").innerHTML += "<div id='oldsite'>Can't find what you're looking for? Try our old website: <a href='http://www.brooksbarn.co.uk'>Old Website (brooksbarn.co.uk)</a> or<a href='mailto:info#brooksbarn.co.uk?Subject=Brooksbarn.com Part Enquiry' target='_top'>E-Mail</a></div>";
?
There are a couple of things you can do, easiest would be to just set the string as innerHTML
(function(){
function addElem () {
var newDiv = document.createElement("div"); //create div
newDiv.id = "oldsite"; //sets id
newDiv.innerHTML = "Can't find what you're looking for? Try our old website: <a href='http://www.brooksbarn.co.uk'>Old Website (brooksbarn.co.uk)</a> or<a href='mailto:info#brooksbarn.co.uk?Subject=Brooksbarn.com Part Enquiry' target='_top'>E-Mail</a>"; //add html to new element
document.getElementById("breadcrump").appendChild(newDiv); //add it to the page
}
if (el.addEventListener) {
window.addEventListener('load', addElem , false);
} else if (el.attachEvent) {
el.attachEvent('onload', addElem );
}
}());
I think you should add these:
1 You are creating a div, not a oldsite tag
var newDiv = document.createElement("div");
2 You need to set the id
newDiv.id = "oldsite";
3 You are originally appending it:
document.body.insertBefore(newDiv, currentDiv.nextSibling);
http://jsfiddle.net/gf6gna1g/
I got a litlle js code that is showing me updates from a feed
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://google.com/");
feed.setNumEntries(1);
var count = 1;
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
var html = "";
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
html = "<h5>" + count++ + ". <a href='" + entry.link + "'>" + entry.title + "</a></h5>";
var div = document.createElement("div");
div.innerHTML = html;
container.appendChild(div);
}
document.write(html);
}
});
}
google.setOnLoadCallback(initialize);
What i want to do is to show the first image from the posts from the feed. i would also like to have the title so entry.title and entry.content
Even though parsing html with regx is big dodo, I will still advise you this, parse your content html with /<img\s+src\s*=\s*(["'][^"']+["']|[^>]+)>/
Or a lazy way is to have a hidden div and do this
var temp = document.createElement( 'div' );
temp.innerHTML = html_str;
var images = temp.getElementsByTagName( 'img' );
First, you must use entry.content instead of entry.title in order to get the full HTML content of the entry. You may have something like this:
var content = entry.content;
var imgArray = content.match( /<img\s+src\s*=\s*(["'][^"']+["']|[^>]+)>/ );
// imgArray[0] would contain the first image (more likely the one that better describe the post)
P.S.: I didn't steal this Regex from actual answer, but it seems that we've got to the same reference for it :-)
UPDATE:
Then, to display it in a container, I would advise you to dynamically create DOM elements to gain more control over it, and in which you will be able to easily associate a value. Something like this:
var dom_h5 = document.createElement('h5');
var dom_entryTitle = document.createElement('div');
dom_entryTitle.className = 'title-classname';
dom_entryTitle.innerHTML = entry.title;
dom_h5.appendChild(dom_entryTitle);
container.appendChild(dom_h5);
To simplify the image part, you could create a separate div and inject the image tag as his innerHTML.
This may help you:
Web API Reference - document.createElement