<div class="container">
<span class="text1">test</span>
<span class="text2">test</span>
</div>
I want to change "text2" to a href in a javascript inside my function like this:
var x=document.getElementsByClassName("text2"); // Find the elements
x.innerHTML="<a href='https://test.com'>test</a>"; // Change the content
so the content of "text2" changes to a hyperlink called "test" which refers to "https://test.com"
you can do it like so:
var element = document.querySelector(".text2"); // Find the first element with the class text2
element.innerHTML = "test"; // Change the content including all HTML elements that might be in there to the value specified escaping the " character
<div class="container">
<span class="text1">test</span>
<span class="text2">test</span>
</div>
the problem was you didn't escaped the " character
you can do it also without the escaping like that:
var element = document.querySelector(".text2"); // Find the first element with the class text2
element.innerHTML = "<a href='https://test.com'>test</a>"; // Change the content including all HTML elements that might be in there to the value specified
<div class="container">
<span class="text1">test</span>
<span class="text2">test</span>
</div>
Not quite sure which approach you need. So here are both:
HTML
<div class="container">
<span class="text1">test</span>
<span class="text2">test</span>
</div>
Approach A - Replace the inner html of the target
document.querySelector(".text2").innerHTML = "<a href='https://test.com'>test</a>";
Approach B - Replace the Span with Anchor
var target = document.querySelector(".text2");
if (target) {
var anchor = document.createElement("a");
anchor.setAttribute("href", "https://www.test.com");
anchor.innerHTML = target.innerHTML;
target.replaceWith(anchor);
}
Related
I need to insert this html tree when I click a button
<div class='img-wrapper'> <img id='immagine_preview' width='200px' height='200px' data-id_immagine='1'><button type='button' class='rimuoviImg' ><span class='fa fa-times'></span></button></div>
I tried this code, but it returns me a body tag with my html inside it.
var stringToHTML = function (str) {
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html');
return doc.body;
};
I need to dynamically add the previous html elements before an upload button (I use a before() method with the stringToHTML function inside and it works). There is a simpler way to do this?. Because I learnt that the documen.createElement doesn't work with a complex argument.
Thank to all community to the help they gave me even with my previous questions.
You can create a html variable with template literal and inside that you can write your html semantic then you can use insertAdjacentHTML()
Use a template string to contain the HTML, and when you click the button use insertAdjacentHTML to add it to an existing element.
const str = `
<div class="img-wrapper">
<img id="immagine_preview" width="200px" height="200px" data-id_immagine="1">
<button type="button" class="rimuoviImg">
<span class="fa fa-times"></span>
</button>
</div>
`
// Cache the element you want to markup to appear,
// and the button
const div = document.querySelector('div');
const button = document.querySelector('button');
// Add a click listener to the button, and insert
// the markup to the chosen element.
button.addEventListener('click', () => {
div.insertAdjacentHTML('beforeend', str);
});
<button>Click</button>
<div />
You could just append the HTML to the element's innerHTML:
document.querySelector('button').addEventListener('click', function() {
document.body.innerHTML += `<div class='img-wrapper'> <img id='immagine_preview' width='200px' height='200px' data-id_immagine='1'><button type='button' class='rimuoviImg' ><span class='fa fa-times'></span></button></div>`;
})
<button>Insert HTML</button>
I have the following HTML...
<html>
<body>
<a class="one" href="example.html">
<span class="two">_____</span></a>
</body>
</html>
Of which the textNode between span tags is changed depending on the href destination of the parent a tag, using the following JavaScript:
var href = document.querySelector(".one").getAttribute("href");
var two = document.querySelectorAll(".two");
var example = document.createTextNode("example");
if (href.startsWith("example")) {
two.forEach(function(twoExample) {
twoExample.appendChild(example);
})
}
This works, however, I have a number of a and span tags that share the same className, for which I'm trying to apply that same JavaScript; so if another a tag had a href of sample, the textNode will change accordingly for the following desired outcome:
var href = document.querySelector(".one").getAttribute("href");
var two = document.querySelectorAll(".two");
var example = document.createTextNode("example");
if (href.startsWith("example")) {
two.forEach(function(twoExample) {
twoExample.appendChild(example);
})
}
<html>
<body
<a class="one" href="example.html">
<span class="two">example</span></a>
</body>
</html>
var example = document.createTextNode("sample");
if (href.startsWith("sample")) {
two.forEach(function(twoSample) {
twoSample.appendChild(sample);
})
}
<html>
<body>
<a class="one" href="sample.html">
<span class="two">sample</span></a>
</body>
</html>
But it doesn't, the first if function seems to override the rest of the other functions, aswell as appending the child to the last element with the same className disregarding href destination.
I'm unsure on a fix to this, hence the question. If anyone has an answer it'd be greatly appreciated!
Note: only Vanilla JavaScript.
I would just do it with simple CSS:
a.one[href^=example]::before {
content: 'example';
}
a.one[href^=sample]::before {
content: 'sample';
}
<a class="one" href="example.html"></a>
<a class="one" href="sample.html"></a>
Of course you can still style ::after pseudo element same as span in case you need to.
In case you still want to learn your JS code, you need to loop over all links and change inner span textContent property. For example like this:
var links = Array.from(document.querySelectorAll('.one'))
links.forEach(function(link) {
var span = link.querySelector('.two')
var href = link.getAttribute('href')
if (href.startsWith('example')) {
span.textContent = 'example'
} else if (href.startsWith('sample')) {
span.textContent = 'sample'
}
})
<a class="one" href="example.html">
<span class="two"></span>
</a>
<a class="one" href="sample.html">
<span class="two"></span>
</a>
Trying to figure out how should I put a span before my_div_class and not to replace all of it. Now it replaces the div, but I don't want to do it. I assume it's something like :before but have no idea how to use it.
<script>
{
var x = document.getElementsByClassName("my_div_class");
x[0].innerHTML = "<span style='color:#ff0000;'>Hello World!<span>";
}
</script>
Use insertAdjacentHTML:
var x = document.getElementsByClassName("my_div_class");
var html = '<span style="color:#ff0000;">Hello World!<span>';
x[0].insertAdjacentHTML('beforebegin', html);
<div class="my_div_class">Hallo</div>
If you want to add the span before the current content of the div, use:
x[0].innerHTML = "<span style='color:#ff0000;'>Hello World!</span> " + x[0].innerHTML;
Notice that you have several errors in your code:
You didn't close the span tag properly.
You don't need those curly brackets.
You may want to add a space at the end of the span to separate it from the current content of the div.
Try this:
var x = document.getElementsByClassName("my_div_class");
x[0].innerHTML = "<span style='color:#ff0000;'>Hello World!</span> " + x[0].innerHTML;
<div class="my_div_class">first div</div>
<div class="my_div_class">another div</div>
<div class="my_div_class">yet another div</div>
<div class="my_div_class">second div</div>
<div class="my_div_class">third div</div>
I am using wordpress and I want to add some html code on page using Javascript. I don't want to make child theme then edit php files. It is risky and I don't know about php.
I want to add a sibling div. This is an example code as default.
<div class="div1">
<div class="div1inside">
Text
</div>
</div>
<div class="div2">
<div class="div2inside">
Text
</div>
</div>
Now I want to add my custom div and its inside html between both div1 and div2.
<div class="mydiv">
<div class="mydivinside">
Text
</div>
</div>
Please let me know how is it possible using Javascript.
There are (at least) two ways, the first:
// document.querySelector() finds, and returns, the first element
// matching the supplied selector (or null, if no element is found):
var el1 = document.querySelector('.div1');
// here we create an adjacent element from the string of HTML,
// the 'afterend' argument states that this adjacent element
// follows the el1 node, rather than preceding it or appearing
// within:
el1.insertAdjacentHTML('afterend', '<div class="mydiv"><div class="mydivinside">Text</div></div>');
var div1 = document.querySelector('.div1');
div1.insertAdjacentHTML('afterend', '<div class="mydiv"><div class="mydivinside">Text</div></div>');
<div class="div1">
<div class="div1inside">
Text
</div>
</div>
<div class="div2">
<div class="div2inside">
Text
</div>
</div>
And the second where you first create that <div> to be inserted, and then use parentNode.insertBefore():
var htmlString = '<div class="mydiv "><div class="mydivinside">Text</div></div>',
// here we create a <div> element:
div = document.createElement('div'),
// we retrieve the element after which the new
// element should be inserted:
div1 = document.querySelector('.div1');
// assign the supplied HTML string to the innerHTML of the
// created element:
div.innerHTML = htmlString;
// and use parentNode.insertBefore to insert the desired element
// (the first argument) before the element identified in the
// second argument, which is the nextSibling of the found
// 'div1' element:
div1.parentNode.insertBefore(div.firstChild, div1.nextSibling);
var htmlString = '<div class="mydiv "><div class="mydivinside">Text</div></div>',
div = document.createElement('div'),
div1 = document.querySelector('.div1');
div.innerHTML = htmlString;
div1.parentNode.insertBefore(div.firstChild, div1.nextSibling);
<div class="div1">
<div class="div1inside">
Text
</div>
</div>
<div class="div2">
<div class="div2inside">
Text
</div>
</div>
References:
document.createElement().
document.querySelector().
Element.insertAdjacentHTML().
Node.firstChild.
Node.insertBefore().
Node.nextSibling.
Node.parentNode.
Use Node#insertBefore method.
// create a div element
var div = document.createElement('div');
// set class name
div.className = 'mydiv';
// set html contents
div.innerHTML = ' <div class="mydivinside"> Text </div>';
// get .div2 element
var ele = document.querySelector('.div2');
// insert before the .div2 element by getting
// its parent node
ele.parentNode.insertBefore(div, ele);
<div class="div1">
<div class="div1inside">
Text
</div>
</div>
<div class="div2">
<div class="div2inside">
Text
</div>
</div>
You can just use the before method to append a div between both div1 and div2. Here is the example:
$('.div2inside').before("<div class='mydiv'><div class='mydivinside'>Text</div></div>");
You could do something like this?
var firstDiv = document.getElementById('div1');
firstDiv.parentNode.insertBefore(document.getElementById('new-div'), firstDiv.nextSibling);
This however assumes that your new-div is already in the dom.
EDIT: to create a the new-div on the fly you can use #david-thomas's solution https://stackoverflow.com/a/41425079/1768337
This link will be helpfull to get the above result.
https://plainjs.com/javascript/manipulation/insert-an-element-after-or-before-another-32/
how can I delete with javascript html tag (for example span) but not the content and the html tags in the content?
one example:
<div id="content">
<span id=1 class="note" >
<p> <span id=1 class="note" >hello! its one example </span> </p>
<li> <span id=1 class="note" >yes,one example </span> </li>
</span>
</div>
the result should be:
<div id="content">
<p> hello! its one example</p><li>yes,one example</li>
</div>
Since you haven't mentioned that you need JQuery, following is the code that I propose:
http://jsfiddle.net/9qgK7/
Relevant code:
span.outerHTML = span.innerHTML;
Reference: https://developer.mozilla.org/en-US/docs/DOM/element.outerHTML
PS: Firefox only started supporting outerHTML since v11 but we are already using v15 :)
In your particular example, its probably best practice to just overwrite the immediate parentNode.
var content = document.getElementById('content'),
span = content.getElementsByTagName('span')[0],
p = content.getElementsByTagName('p')[0];
content.innerHTML = span.innerHTML;
Can easily be done with Jquery:
$('span.note').each(function(){
$(this).replaceWith($(this).html());
});
If you can use jQuery, try something like this
var newContent = $("#content span").html();
$("#content").html(newContent);
EDIT
Pure JS solution
var spans = document.getElementById("content").getElementsByClassName("note");
var out = "";
for (var i = spans.length - 1; i >= 0; i--) {
out += spans[i].innerHTML;
}
document.getElementById("content").innerHTML = out;
jsFiddle Example