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>
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>
<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);
}
I can't adjust my text to be center aligned. I tried to put css code in onmouseover="hover('')" but it doesn't work. What is the get around for this?
Middle circle with id="content" that changes the tag on hover
<div id="circle">
<p id="content">
<b><span>Services</span></b>
</p>
</div>
JS Code that I included in the html tag to change content on hover
<a href="">
<div onmouseover="hover('<b>BPO</b>')" onmouseout="hover('<b>Services</b>')" class="scaling" id="circle-2">
<img src="/static/img/2.png" onmouseover="this.src='/static/img/2b.png'" onmouseout="this.src='/static/img/2.png'" style="margin-top:5px;" width=100px/>
</div>
</a>
<a href="">
<div onmouseover="hover('<b>Web Development</b>')" onmouseout="hover('<b>Services</b>')" class="scaling" id="circle-3">
<img src="/static/img/4.png" onmouseover="this.src='/static/img/4b.png'" onmouseout="this.src='/static/img/4.png'" style="margin-top:5px;" width=100px/>
</div>
</a>
JS Code that changes the content of the <p> tag
function hover(description) {
console.log(description);
document.getElementById('content').innerHTML = description;
}
everything is working properly but I can't adjust the text to be in the center regard less of the <p> tag length .
The main question is how do i add css code in onmouseover="hover('')"
What i want it to look like
what it looks like
Your code really needed a lot of cleaning up.
You should separate the HTML, CSS and JavaScript. After doing this, debugging is SO much easier and the code is much simpler to follow.
In addition, you had a great deal of duplication in your code. Again, using CSS and JavaScript can remove that redundancy. For example, styling is done with CSS, not HTML. Tags like <b> are deprecated and should no longer be used. By creating CSS styles that incorporate font-weight:bold and applying those styles properly, we can get rid of all the <b> and </b> tags.
// Get all DOM references:
var content = document.getElementById('content');
var cir2 = document.getElementById("circle-2");
var cir3 = document.getElementById("circle-3");
var img1 = document.getElementById("img1");
var img2 = document.getElementById("img2");
// Attach event handlers:
cir2.addEventListener("mouseover", function(){ hover('BPO') });
cir2.addEventListener("mouseout", function(){ hover('Services') });
cir3.addEventListener("mouseover", function(){ hover('Web Development') });
cir3.addEventListener("mouseout", function(){ hover('Services') });
img1.addEventListener("mouseover", function(e){ changeSource(e,'http://plumseattle.com/wp-content/uploads/2016/01/linkedin-logo.jpg') });
img1.addEventListener("mouseout", function(e){ changeSource(e, 'https://cdn3.iconfinder.com/data/icons/free-social-icons/67/facebook_circle_color-256.png') });
img2.addEventListener("mouseover", function(e){ changeSource(e, 'http://seeklogo.com/images/S/snapchat-logo-2D9C3E7ADA-seeklogo.com.png') });
img2.addEventListener("mouseout", function(e){ changeSource(e, 'https://www.seeklogo.net/wp-content/uploads/2011/06/Twitter-icon-vector-400x400.png') });
function hover(description) {
//console.log(description);
content.textContent = description;
}
function changeSource(evt, source){
evt.target.src = source;
}
content > span { font-weight: bold;}
.scaling { font-weight:bold; }
.img { margin-top:5px;width:100px; }
<div id="circle">
<p id="content">
<span>Services</span>
</p>
</div>
<a href="">
<div class="scaling" id="circle-2">
<img id="img1"
src="https://cdn3.iconfinder.com/data/icons/free-social-icons/67/facebook_circle_color-256.png"
class="img">
</div>
</a>
<a href="">
<div class="scaling" id="circle-3">
<img id="img2"
src="https://www.seeklogo.net/wp-content/uploads/2011/06/Twitter-icon-vector-400x400.png"
class="img">
</div>
</a>
Typically, if you want some element to listen to "mouseover" event, the best way to go is to use EventTarget#addEventListener. Just like this:
const node = document.getElementById('hover');
node.addEventListener('mouseover', () => {
node.innerText = `Last time mouseover'd at ${new Date()}.`;
});
So, now, you need to update children of #content and src attribute of an image under mouse cursor.
The HTML would look like this:
<p id="content">
Services
</p>
<a href="">
<div class="scaling" id="circle-2">
<img src="/static/img/2.png" />
</div>
</a>
<a href="">
<div class="scaling" id="circle-3">
<img src="/static/img/2.png" />
</div>
</a>
while JS code would look like this:
const content = document.getElementById('content');
const circle2 = document.getElementById('circle-2');
const circle3 = document.getElementById('circle-3');
circle2.addEventListener('mouseover', () => {
circle2.children[0].src = '/static/img/2b.png';
content.innerText = 'BPO';
});
circle2.addEventListener('mouseout', () => {
circle2.children[0].src = '/static/img/2.png';
content.innerText = 'Services';
});
circle3.addEventListener('mouseover', () => {
circle3.children[0].src = '/static/img/4b.png'
content.innerText = 'Web Development';
});
circle3.addEventListener('mouseout', () => {
circle3.children[0].src = '/static/img/4.png'
content.innerText = 'Services';
});
(check out this fiddle).
In html I am having the following tags:
<span id=M26>2011-2012</span>
<div id=c26 STYLE="display:none">
<span id=M27>2012-2013</span>
<div id=c26 STYLE="display:none">
On Clicking on 2011-2012 or on 2012-2013 I want to set display property of div tag.
I am using the following Javascript code for this and I am calling the Javascript function in body tag. The output is showing style and display is not an object or property.
<script language="javascript">
function clickHnadler()
{
var xid= document.getElementsByTagName("span");
var xsp= xid[0].id;
alert("Span id is "+xsp);
if(xsp.charAt(0)=="M")
{
var oC = document.all("C"& xsp.substring(1,2));
if(oC.STYLE.display == "none")
{
oC.Style.Display = "";
}
else{
oC.Style.Display = "none";
}
}
}
</script>
use jquery:
you can pass in the function the element or the Id:
ex:
<span id=M26>2011-2012</span>
function clickHnadler(element)
{
var id = $(element > span).attr(id);
id[0] = 'c'; //not the nicest way, maybe use a replace or something like that
$(id).show(); //or $(id).css('display','list');
}
You may use clickHandler has following way,
function clickHandler(e) {
window.document.links[0].handleEvent(e);
}
You need to bind event spacifically to elements you want to handle click for. for more information please refer following link,
http://docs.oracle.com/cd/E19957-01/816-6409-10/evnt.htm#1009606
Based on what i understand from your question, I come up with this.
<script type="text/javascript" src="jquery1.8.js"></script>
<span id=M26>2011-2012</span>
<div id=c26 STYLE="display:none">
2011-2012 details</div>
<br />
<span id=M27>2012-2013</span>
<div id=c26 STYLE="display:none">
2012-2013 details
</div>
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