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();
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've dinamically created a div with the code below:
typebox.innerHTML += "<div id='idtypebox' class='typebox'><img id='typeImg' width='30px' height='30px' src="+d[o].src+"></div>";
My intention is to remove completely the innerHTML I created, by changing the innerHTML that had created the img and if change the form A to B, those images will be removed.
function SelectCheck() {
var select_val = $('#Check').val();
// using this to remove typeimg
var toRemove = document.getElementById('typeImg');
toRemove.parentNode.removeChild(toRemove);
if (select_val) {
ajax_json_gallery("Img/"+select_val);
}
return;
}
$(document).ready(function() {
$("#Check").change(SelectCheck).change();
});
I tried this code by on button and it works, but if I put in jQuery selection I get an error
var toRemove = document.getElementById('typeImg');
toRemove.parentNode.removeChild(toRemove);
Why not just :
$("#typeImg").remove();
And the complete code :
function SelectCheck(){
var select_val = $('#Check').val();
// using this to remove typeimg
$("#typeImg").remove();
if(select_val){
ajax_json_gallery("Img/"+select_val);
}
return;
}
jQuery(document).ready(function($) {
myVar=$("#d1 [href]").html();
var href = $(myVar).attr('src');
$("#d1").html('');
$("#d1").html('<img src="'+href+'" class="images_responsive_mode">').removeAttr("href");
});
</script>
this is one of the script which i created for remove the class assigned by wordpress and to assign new class for responsive image , if it useful for you do this !
you can use childNodes to remove the innerHtml
var toRemove = document.getElementById('typeImg');
toRemove.parentNode.removeChild(toRemove.childNodes[0])
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/
This is a follow up to this question:
How to replace DOM element in place using Javascript?
I wasn't the OP but I am facing a similar situation. The initial question was "how to replace an anchor element with a span using Javascript. The answer that was given (thank you Bjorn Tipling ) was to use replaceChild(), with the following example:
<html>
<head>
</head>
<body>
<div>
<a id="myAnchor" href="http://www.stackoverflow">StackOverflow</a>
</div>
<script type="text/JavaScript">
var myAnchor = document.getElementById("myAnchor");
var mySpan = document.createElement("span");
mySpan.innerHTML = "replaced anchor!";
myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
</body>
</html>
My follow up is: how to add / insert an id (e.g., "xyz")and a function (e.g., onmouseout='doWhatever(this)') to the replaced DOM element?
You can add an id property by simply setting it:
mySpan.id = "xyz";
And you can attach an event like so:
mySpan.onmouseout = function() {
doWhatever(this);
}
I would avoid setting event attributes when dynamically creating DOM elements. Assigning the event handlers programmatically is the right way to go.
mySpan.id = "abcd123";
mySpan.onclick = function () { console.log(this.id + " was clicked"); };
Once you have your HTML element cached to a variable, you can just keep using that variable to work with it.
Use this:
<script type="text/JavaScript">
var myAnchor = document.getElementById("myAnchor");
var mySpan = document.createElement("span");
mySpan.appendChild(document.createTextNode("replaced anchor!"));
mySpan.id = "xyz";
mySpan.onmouseout = function() {
doWhatever(this);
};
myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
I want to dynamically create a div element with id="xyz". Now before creating this, I want to remove any other div with id ="xyz" if it exists. How can i do it?
var msgContainer = document.createElement('div');
msgContainer.setAttribute('id', 'xyz'); //set id
msgContainer.setAttribute('class', 'content done'); // i want to add a class to it. it this correct?
var msg2 = document.createTextNode(msg);
msgContainer.appendChild(msg2);
document.body.appendChild(msgContainer);
}
How can i remove all divs with id =xyz if they exist before executing above code?
Removing:
var div = document.getElementById('xyz');
if (div) {
div.parentNode.removeChild(div);
}
Or if you don't control the document and think it may be malformed:
var div = document.getElementById('xyz');
while (div) {
div.parentNode.removeChild(div);
div = document.getElementById('xyz');
}
(Alternatives below.)
But you only need the loop with invalid HTML documents; if you control the document, there's no need, simply ensure the document is valid. id values must be unique. And yet, one sees plenty of documents where they aren't.
Adding:
var msgContainer = document.createElement('div');
msgContainer.id = 'xyz'; // No setAttribute required
msgContainer.className = 'someClass' // No setAttribute required, note it's "className" to avoid conflict with JavaScript reserved word
msgContainer.appendChild(document.createTextNode(msg));
document.body.appendChild(msgContainer);
If you don't like the code duplication in my loop above and you think you need the loop, you could do:
var div;
while (!!(div = document.getElementById('xyz'))) {
div.parentNode.removeChild(div);
}
or
var div;
while (div = document.getElementById('xyz')) {
div.parentNode.removeChild(div);
}
...although that last may well generate lint warnings from various tools, since it looks like you have = where you mean == or === (but in this case, we really do mean =).