I'm getting data from Wordpress, which contains HTML with inline styles. Before I insert this HTML into my React website, I would like to remove all inline styles. For example, I get something like:
<div style='height: 500px'>
<img style='height: 300px; width: 250px'/>
... more elements with inline styles
</div>
I'm looking for a clean way of doing this because I've tried using other solutions on SO and they use Jquery and other JS methods which would not work since I'm using React to build my website.
You call select all the html tags and using document.querySelectorAll('*') and iterate through each one of them and using removeAttribute, removes style attribute.
const htmlString = `<div style='height: 500px'>
<img style='height: 300px; width: 250px'/>
<p> text</p>
<div style="color: red">Red text</div>
... more elements with inline styles
</div>`;
const htmlNode = document.createElement('div');
htmlNode.innerHTML = htmlString;
htmlNode.querySelectorAll('*').forEach(function(node) {
node.removeAttribute('style');
});
console.log(htmlNode.innerHTML);
You can find all tag in your body then use removeAttribute to remove style attribute.
function remove(){
var allBodyTag = document.body.getElementsByTagName("*");
for (var i = 0; i < allBodyTag.length; i++) {
allBodyTag[i].removeAttribute("style");
}
}
<button onClick="remove()">Remove </button>
<div style='height: 500px'>
This is text
<img style='height: 50px; width: 250px'/>
</div>
Related
I have the following structure .. I would like to remove div.son but keepdiv.grandson, is that possible ?! or changing your <tag> would also be a solution .. ex: changing from <fieldset> to a <div>, remembering that I do not have access to HTML, every change must be done using ** javascript **!
<div class="father">
<fieldset class="son">
<div class="grandson">Content here</div>
<div class="grandson">Content here</div>
<div class="grandson">Content here</div>
<div class="grandson">Content here</div>
</fieldset>
</div>
I tried to use the removeChild () function of ** javascript **, but it removes the entire element.
It's possible with vanilla JavaScript by deep cloning the node of grandson before removing anything else. and then appending it back to the parent. Of course if you want to place it somewhere else, you need to append needed logic of DOM traversing. (CSS section is only for visual validation of the result)
const grandson = document.querySelector('.grandson');
const father = grandson.closest('.father');
const clonedGrandson = grandson.cloneNode(true);
father.querySelector('.son').remove();
father.appendChild(clonedGrandson);
.father {
background-color: red;
padding: 20px;
}
.son {
background-color: blue;
padding: 20px;
}
.grandson {
background-color: green;
padding: 20px;
}
<div class="father">
<fieldset class="son">
<div class="grandson">
<p>Save me</p>
</div>
</fieldset>
</div>
You may take a look at this answer, try to use the search bar next time.
https://stackoverflow.com/a/170056/10944905
In case you just want to jump all over the answer.
var cnt = $(".remove-just-this").contents();
$(".remove-just-this").replaceWith(cnt);
I want to append multiple copies of div with id hello into the div with id container. How do I do this using javascript?
<div id="container">
</div>
<div id="hello">
<p>Hello</p>
</div>
Using cloneNode and appendChild.
Since ids should be unique in a document, I switched things to use a class hello instead.
function makeCopy() {
const target = document.getElementById("container");
const source = document.querySelector(".hello");
const clone = source.cloneNode(true);
target.appendChild(clone);
}
.hello {
padding: 3px;
margin: 3px;
border: 1px dotted orange;
}
<div id="container">
This is the container.
</div>
<button onclick="makeCopy()">Add a clone of hello above</button>
<div class="hello">
<p>Hello</p>
</div>
https://www.w3schools.com/jsref/met_node_appendchild.asp
check this out, it will solve your problem, BUT use a class for the tag not an ID. IDs are unique, a class is for multiple elements.
you can call class in CSS like this
.className {
/*CODE*/
}
you can use append() method:
$(document).on('click', function(){
$('#container').append( $('#hello') );
});
I have a function that changes the src attribute of an icon when this one is clicked.
I also want it to hide the closest icon of the class fave_icon. I tried the following but it's not working:
function trash(event, trashcan){
event.stopPropagation();
if (trashcan.getAttribute('src') == "Iconos/tacho.png")
{
trashcan.src = "Iconos/warning.png"; //this works ok
var heart = trashcan.closest(".fave_icon");
heart.style.visibility = "hidden"
}
}
Basically I want to hide the closest element with class fave_icon to trashcan.
On the HTML I have this several times:
<button class="accordion">
<div>
<img src="Iconos/heart.png" onclick="fav(event,this);" alt="Fave" class="fave_icon">
</div>
<div>
<img src="Iconos/tacho.png" onclick="trash(event,this);" alt="Delete" class="delete_icon">
</div>
</button>
If fave_icon is a class then you have to place dot (.) before the class name as part of the selector.
Change var heart = trashcan.closest("fave_icon");
To
var heart = trashcan.closest(".fave_icon");
Based on the code and HTML you have provided you can do something like the following:
function trash(event, trashcan){
event.stopPropagation();
if (trashcan.getAttribute('src') == "Iconos/tacho.png"){
trashcan.src = "Iconos/warning.png"; //this works ok
var heart = trashcan.closest('button').querySelector('.fave_icon');
heart.style.visibility = "hidden";
}
}
<button class="accordion">
<div>
<img src="Iconos/heart.png" onclick="fav(event,this);" alt="Fave" class="fave_icon">
</div>
<div>
<img src="Iconos/tacho.png" onclick="trash(event,this);" alt="Delete" class="delete_icon">
</div>
</button>
From the trash icon, you go up a level to the div, select the previousElementSibling to get the heart's div, and then go down a level to the heart image itself.
Because the element is already included in the event target, you don't need to pass this. Or, even better, if you select the trash image first, you can avoid this entirely and use explicit variable names, which are easier to understand and debug.
But inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener
Another problem is that buttons should not have closing tags. Use a container element instead, like a div.
So, try something like this:
document.querySelectorAll('img[src="Iconos/tacho.png"]').forEach(img => {
img.onclick = () => {
const heartImg = img.parentElement.previousElementSibling.children[0];
heartImg.style.visibility = 'hidden';
};
});
<div class="accordion">
<div>
<img src="Iconos/heart.png" alt="Fave" class="fave_icon">
</div>
<div>
<img src="Iconos/tacho.png" alt="Delete" class="delete_icon">
</div>
</div>
you can add a class to the clicked element and use the general sibling combinator if the two items are adjacent.
document.getElementById("hide")
.addEventListener("click", (event) => {
event.target.classList.add('active');
}, false);
#hide.active~.element {
visibility: hidden;
}
#hide {
cursor: pointer;
}
.accordion {
padding: 15px;
background: lightgrey;
border-bottom: 1px solid grey;
}
.accordion div {
color: black;
margin-right: 20px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/icono/1.3.0/icono.min.css" rel="stylesheet" />
<div class="accordion">
<div class="icono-trash" id="hide"></div>
<div class="element icono-heart"></div>
</div>
dI am succesfully placing text in a div using javascript. However I also want to add images to the text but my javascript method does not seem to accept this. I am using the following code for the text:
document.getElementById("myDiv").innerHTML = "This a bit of text";
See the Fiddle here
Just adding an img tag within the text hasn't worked. Anyone?
Eddy.
And what if I wanted to add the possibility to enlarged the photo using the following script.
<div class="slider jcarousel fancybox" data-jcarousel="true" style="position: relative; width: auto; margin-top: -1px; z-index: 99;">
<ul style="left: 0px; top: 0px; width: 100%;">
<li class="product slide" style="width: auto; border: none;"><a class="zoom first" rel="" href="https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300" title=“Test image”><img src="https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300" alt=“Test image“ /></a>
</li>
</ul>
</div>
How would I place this within the text?
You should be able to insert images with innerHtml. Just use '' marks instead of "".
Like this:
document.getElementById("myDiv").innerHTML = 'This a bit of text <img src="https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300" />';
Fiddle
To add images in HTML text you must escape quotes using \ before or use ' instead of " in attributes or string.
If you don't that, then you'll see an error in the browser's console.
This is wrong:
document.getElementById("myDiv").innerHTML="<img src="img.png">"//img.png is outside of the string
Examples:
document.getElementById("myDiv").innerHTML="<img src=\"img.png\"/>"
document.getElementById("myDiv").innerHTML='<img src="img.png">'
document.getElementById("myDiv").innerHTML="<img src='img.png'/>"
How did you try to add the image?
document.getElementById("myDiv").innerHTML = " <img src=' // image path ...'/>This a bit of text";
this way you can add image easily. but please make sure that you are addind image with proper path
OR if it will not work then,
add <img /> tag in HTML. like:
<div id="myDiv">
<img src="..image path..." />
</div>
You shouldn't use innerHTML. This is a better way of doing it:
var myDiv = document.getElementById("myDiv");
myDiv.textContent = "This a bit of text";
var myImg = new Image();
myImg.src = "http://placehold.it/100x50";
myDiv.appendChild(myImg);
<div id="myDiv">
</div>
i want to add following div runtime with this style to other div
<div id="grid" style="width: 100%; height:180px;">
</div>
parent div:
<div id="graph" class="tabdiv"></div>
I want to add grid div to graph div with given style,how to achive this with jquery or javascript,plz help
In JQuery:
$('#graph').append('<div id="grid" style="width: 100%; height:180px;"></div>')
try
$(document).ready(function () {
var newdiv = $('<div/>', { style: "width: 100%; height:180px;", id: "grid" });
$("#graph").append(newdiv);
});
You can do it by following two ways:
1> Use .append() when you want parent as return control
$('#graph').append('<div id="grid" style="width: 100%; height:180px;"></div>')
or
2> Use .appendTo() when you want child as return control
var childDiv='<div id="grid" style="width: 100%; height:180px;"></div>';
childDiv.appendTo($('#graph'))
Try this
$('<div></div>', {class:'tabdiv', id:'graph', text:'Hi'}).appendTo('body')
Fiddle Demo
Use jquery .append()
$('#graph').append("<div id='grid' style='width: 100%; height:180px;'></div>");
FIDDLE
Here's native JavaScript:
var
node = document.getElementById('graph'),
template = '<div id="grid" style="width: 100%; height:180px;"></div>'
node.innerHTML=template
//or you can ...
node.innerHTML+=template
may the answer can help u.