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/
Related
First, sorry I'm not good with javascript.
HTML:
<div id="Comment-ID">
<p class="comment-content">...</p>
</div>
The javascript: (Edit: Added the whole code)
<script type='text/javascript'>
function autoloadmore() {
var loadmoreClass = document.getElementsByClassName("loadmore")[0];
var loadmoreChild = loadmoreClass.querySelector('a')
if (loadmoreClass) {
loadmoreChild.click();
}
}
//<![CDATA[
function InsertarImagenVideo(id) {
var IDelemento = document.getElementById(id),
sustituir = IDelemento.innerHTML;
sustituir = sustituir.replace(/\[img\](.[^\]]*)\[\/img\]/ig, "<img class='img-comentarios' src='$1'\/>");
document.getElementById(id).innerHTML = sustituir;
}
//]]>
window.onload = function() {
autoloadmore();
setTimeout(function(){
InsertarImagenVideo('Comment-ID');
},3000);
};
</script>
"InsertarImagenVideo" replaces some text inside with an image. Instead of using it on "Comment-ID", I want to use it on "Comment-class".
Note: I can't edit the HTML.
I couldn't find anything when I searched, or maybe I didn't know how to look. Can someone help me with this?
You can use document.querySelector to select an element by class:
Update this line:
var IDelemento = document.getElementById(id),
to var IDelemento = document.querySelector(id),
and pass the class selector to your method InsertarImagenVideo
setTimeout(function(){
InsertarImagenVideo('.comment-content');
},3000);
I found a simple way to insert an image into the <p class="comment-content">...</p> element by grabbing the parent <div id="Comment-ID">.
I'm assuming that you need to grab the unique id to then access the inner <p> element to replace the existing text with an image. This code grabs the unique id element, then grabs the first <p> tag using .getElementsByTagName('p')[0]. One thing I did add is a proper image load script to update the <p> tag with the image once it has been loaded (maybe this removes the need for that setTimeout function you have?).
let classElement = document.getElementById("Comment-ID").getElementsByTagName('p')[0];
let imageObject = new Image();
imageObject.src = `https://www.clipartmax.com/png/full/1-14442_smiley-face-png-smiley-png.png`;
imageObject.onload = function() {
classElement.innerHTML = `<img id="myImg" src="${imageObject.src}" />`;
let imageElement = document.getElementById(`myImg`);
imageElement.width = 100;
imageElement.height = 100;
};
Here's a JSFiddle demo of the upper code in action.
Hope this helps :)
I need to append some html to an existing element using pure javaScript:
function create(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
var target = document.querySelectorAll(".container-right");
var fragment = create(
'<div class="freetext"><p>Some text that should be appended...</p></div>'
);
document.body.insertBefore(fragment, document.body.childNodes[0]);
It's kind of working, but I have two questions:
How can I make sure that the html fragment is appended to the div with the class container-right and not just the body? Changing the last line to document.body.insertBefore(fragment, target); doesn't work.
How can I insert the html after the content in the target element - after the existing content - like jQuery's append()?
Any help is much appreciated.
JsFiddle here.
Well, I know this works:
let elem = document.querySelector ( 'css-selector (id or class)' )
That should give you your element. Then you do this:
elem.innerHTML = elem.innerHTML + myNewStuff;
That'll append your html to the innerHTML of the element. I tried it quickly, it works.
var target = document.querySelector(".container-right");
var p = document.createElement('p');
p.innerHTML = "Some text that should be appended...";
var div = document.createElement('div');
div.appendChild(p);
var fragment = document.createDocumentFragment();
fragment.appendChild(div);
target.appendChild(fragment);
JSFiddle
Try this:
var target = document.querySelector(".container-right");
target.innerHTML += '<div class="freetext"><p>Some text that should be appended...</p></div>';
Based on this answer to a similar question, I have found that insertAdjacentHTML is a good fit for this kind of problems.
I haven't tested it on a Node List, but with a single node it works perfectly.
insertAdjacentHTML has a great browser compatibility (back to IE4), plus it lets you decide where you want to insert the HTML (see here).
var target = document.querySelector(".container-right");
var newContent = '<div class="freetext"><p>Some text that should be appended...</p></div>';
target.insertAdjacentHTML('beforeend', newContent);
document.querySelectorAll('.container-right').forEach(elm=>{
elm.innerHTML += '<div class="freetext"><p>Some text that should be appended...</p></div>';
});
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>
I figured I would get fancy and use vanilla JavaScript during a jQuery event. The idea is that on click of a heading, I want to slide up a div (which works) and replace the tag clicked on to a larger heading.
From what I've read around, this can be caused by the parentNode referencing an element that's not the actual parent, but after checking it appears to be selecting the element that's directly above it.
So... here's the code!
HTML (in Jade)
.policy-container
h6.policy-heading Policies
.policy-list
.content-we-are-hiding
.not-actually-important
jQuery
$('.policy-heading').click(function() {
var self = this;
if (this.classList.contains('closed')) {
$(this).next().slideDown(300);
this.parentNode.replaceChild(self, '<h6 class="policy-heading">Policies</h6>');
} else {
$(this).next().slideUp(300);
this.parentNode.replaceChild(self, '<h2 class="policy-heading closed">Policies</h2>');
}
});
Everything seems pretty standard. Luckily I can just take care of this with jQuery, however I'd rather be using vanilla JS here. Any ideas why this isn't working?
As has been pointed out, replaceChild takes two nodes.
The following will work with native JS wrapped inside jQuery, as you've specified:
$('.policy-heading').click(function () {
var self = this,
h2 = document.createElement('h2'),
h6 = document.createElement('h6');
h2.class = "policy-heading closed";
h2.innerHTML = "Policies";
h6.class = "policy-heading";
h6.innerHTML = "Policies";
if (this.classList.contains('closed')) {
$(this).next().slideDown(300);
this.parentNode.replaceChild(h6, self);
} else {
$(this).next().slideUp(300);
this.parentNode.replaceChild(h2, self);
}
});
replaceChild takes two nodes, you are giving it a node and a string.
It looks like you'd be much better off just sticking with jQuery and using toggle functions for the sliding and class change.
try this :
.click(function(this)
you also need some debugging to understand what is going on I would advice you to use :
console.log(this)
use this :
el = document.createElement('h6');
el.class = "policy-heading";
el.innerHTML = "Policies";
this.parentNode.replaceChild(self, el);
As everyone pointed out, .replaceChild accepts two DOM elements, rather than the string like I was using. I also had its arguments backwards, the first is for the new element, the second is the replaced element.
Example code that works
$('.policy-container').on('click', '.policy-heading', function() {
var self = this,
newElement;
if (this.classList.contains('closed')) {
newElement = document.createElement( 'h6' );
newElement.classList.add('policy-heading');
newElement.innerHTML = 'Policies';
} else {
newElement = document.createElement( 'h2' );
newElement.classList.add('policy-heading');
newElement.classList.add('closed');
newElement.innerHTML = 'Policies';
}
$(this).next().slideDown(300, function() {
self.parentNode.replaceChild( newElement, self );
});
});
How can I find <div> tags with no id?
This is my markup:
<body>
<div>this is a text</div>
</body>
This is my JavaScript used to add divs to the page:
var show = function () {
var htmlNode = document.createElement('DIV');
document.body.insertBefore(htmlNode, document.body.childNodes[0]);
htmlNode.innerHTML = 'this is a text';
};
if (window.addEventListener) {
window.addEventListener("load", show, true);
} else {
}
window.attachEvent("onload", show);
How can I remove this after the page is loaded? By putting the JavaScript in the bottom of the page?
If you keep the htmlNode handle, you already have a route to remove the element.
document.body.removeChild(htmlNode);
You just need the htmlNode variable to be in a scope shared by the show function and the function your write to remove it:
var htmlNode;
var show = function () {
htmlNode = document.createElement('DIV');
document.body.insertBefore(htmlNode, document.body.childNodes[0]);
htmlNode.innerHTML = 'this is a text';
};
var hide = function () {
document.body.removeChild(htmlNode);
};
Alternatively, you can give it an id...
htmlNode = document.createElement('DIV');
htmlNode.id = 'MyElementId';
With jQuery:
$('DIV:not([id])').remove();
Are you trying to remove just this one DIV, or any without IDs?
If you're trying to remove all DIVs without IDs, use getElementsByTagName('div') to retrieve all DIVs, iterate through them and check the for the absence of the ID attribute.
document.body.childNodes[0].removeChild();