I am new to javascript, I am trying to append a img tag inside a div tag.
but it is not concatinating with already existing elements inside the div.
This is my HTML code:
<div class="ce_label">
<span>some text</span>
<span>some text</span>
</div>
My javascript Code :
var sel = '.ce_label';
var toolTemplate = [
'<img src="smiley.gif" alt="Smiley face" height="42" width="42">'
];
window.onload = function() {
var x = document.querySelectorAll(sel);
var commentHtml = toolTemplate.join('');
for (var i = 0; i < x.length; i++) {
x[i].appendChild = commentHtml;
}
};
So my output should be :
<div class="ce_label">
<img src="smiley.gif" alt="Smiley face" height="42" width="42">
<span>some text</span>
<span>some text</span>
</div>
But I could not get this output..
Can anyone help me to fix it???
Thanks in advance.
This line
x[i].appendChild = commentHtml;
tries to assign a string to the element's appendChild property, which refers to a function you can't overwrite.
If you want to replace the element's content with that HTML, assign to innerHTML:
x[i].innerHTML = commentHtml;
If you want to append to the element's curent contents, call the element's insertAdjacentHTML method:
x[i].insertAdjacentHTML("beforeend", commentHtml);
Related
I'm new to JavaScript and expect a answer from expert.
Suppose following is my piece of content -
<p> This is the first paragraph </p>
<p> This is the second paragraph </p>
and, I want to add few block of code after every paragraph and code became following -
<p> This is the first paragraph </p>
<figure class="x">
<iframe width="300" height="250" style="border:0; margin:0;" src="#">
</iframe>
</figure>
<p> This is the second paragraph </p>
<figure class="x">
<iframe width="300" height="250" style="border:0; margin:0;" src="#">
</iframe>
</figure>
You can try this javascript to get started.
// get all "p" tags
var elements = document.getElementsByTagName('p');
for (var i = 0; i < elements.length; i++) {
// create figure
const figure = document.createElement("figure");
figure.className = "x";
// create iframe
const iframe = document.createElement("iframe");
iframe.setAttribute("width", "300");
iframe.setAttribute("height", "250");
iframe.setAttribute("href", "#");
iframe.style.border = 0;
iframe.style.margin = 0;
figure.appendChild(iframe);
// append to "p" tag
elements[i].parentNode.insertBefore(figure, elements[i].nextSibling);
}
You need to create figure HTML element that has a child iframe and then add the figure element after every p
How to insert an element after another element in JavaScript without using a library?
const paras = document.querySelectorAll("p");
function createIframe(width, height, style, src) {
const iframe = document.createElement("iframe");
iframe.setAttribute("width", width);
iframe.setAttribute("height", height);
iframe.setAttribute("style", style);
iframe.setAttribute("src", src);
return iframe;
}
function createFigureElement() {
const figure = document.createElement("figure");
figure.classList.add("x");
figure.appendChild(createIframe("300", "250", "border:0; margin:0;", "#"));
return figure;
}
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
paras.forEach((p) => {
insertAfter(p, createFigureElement());
});
<p> This is the first paragraph </p>
<p> This is the second paragraph </p>
Probably the shortest way:
document.querySelectorAll('p').forEach(p => {
p.insertAdjacentHTML('afterEnd',
`<figure class="x">
<iframe width="300" height="250" style="border:0; margin:0;" src="#"></iframe>
</figure>`
);
})
<p> This is the first paragraph </p>
<p> This is the second paragraph </p>
I Hope you can help me.
When I click button it adds night before file extension ex.(interior-1.jpg to interior-1-night) but it only affects the first image which is interior-1.jpg.
What I want is to add "night" text before the file extension of all images under the "image" ID.
Here is my html code
<button onclick="changeMode()">switch</button>
<img id="image" src="interior-1.jpg"/>
<img id="image" src="interior-2.jpg"/>
<img id="image" src="interior-3.jpg"/>
<img id="image" src="interior-4.jpg"/>
<img id="image" src="interior-5.jpg"/>
Here is my javascript code
<script>
function changeMode() {
var filename = document.getElementById("image").src;
var modfilename = filename.replace(/(\.[\w\d_-]+)$/i, '-night$1');
document.getElementById("image").src = modfilename;
</script>
}
You should never use same id name on elements in the dom. Instead use same class name. To apply the src on all the img tag get all the tags using document.getElementsByClassName. Iterate over each element and change the src using a forEach loop
function changeMode() {
var filename = document.getElementsByClassName("image");
var a = '';
Object.values(filename).forEach((e) => {
a = e.src;
var modfilename = a.replace(/(\.[\w\d_-]+)$/i, '-night$1');
e.src = modfilename;
})
}
<button onclick="changeMode()">switch</button>
<img class="image" src="interior-1.jpg" />
<img class="image" src="interior-2.jpg" />
<img class="image" src="interior-3.jpg" />
<img class="image" src="interior-4.jpg" />
<img class="image" src="interior-5.jpg" />
The problem is that you are getting your element by GetElementById which only returns one element. You should change the id tag to name like this:
<img name="image" src="interior-1.jpg"/>
Then you should be able to retrieve all the elements using var els = document.getElementsByName('image');
now you need to change their file names, so
for (let i = 0; i<els.length; i++){
els[i].src = els[i].src.replace(/(\.[\w\d_-]+)$/i, '-night$1');
}
Here is my two cents. Use classes. This way you can query multiple elements instead of just one. Then apply your changes to each element using, in this case, a forEach.
The elements returend from document.querySelectorAll is a nodeList. That's why I use Array.prototype.forEach.call.
function changeMode() {
const imageNodes = document.querySelectorAll(".image");
Array.prototype.forEach.call(imageNodes, (node) => {
let modfilename = node.src.replace(/(\.[\w\d_-]+)$/i, '-night$1');
node.src = modfilename
})
}
<button onclick="changeMode()">switch</button>
<img class="image" src="interior-1.jpg"/>
<img class="image" src="interior-2.jpg"/>
<img class="image" src="interior-3.jpg"/>
<img class="image" src="interior-4.jpg"/>
<img class="image" src="interior-5.jpg"/>
I have the following HTML:
<div class="sidenav-contact__types">
<div class="sidenav-contact__type js-sidenav-contact__type" data-contact-type="call-me-back">
<figure>
<svg class="sidenav-contact__icon"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/etc/designs/site/img/icons.svg#caller-inverse"></use></svg>
</figure>
<h5>Call me back</h5>
<p>Talk to a Representative about our range.</p>
</div>
<div class="sidenav-contact__type js-sidenav-contact__type" data-contact-type="contact-us">
<figure>
<svg class="sidenav-contact__icon"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/etc/designs/site/img/icons.svg#info-inverse"></use></svg>
</figure>
<h5>Contact Us</h5>
<p>For FAQs, feedback, suggestions or media.</p>
</div>
<a class="sidenav-contact__type" href="http://site" data-contact-type="new button">
<figure>
<svg class="sidenav-contact__icon"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/etc/designs/site/img/icons.svg#recall-inverse"></use></svg>
</figure>
<h5>Information</h5>
<p>vehicle is affected.</p>
</a>
</div>
What I'm trying to do is detect when a user clicks inside a div or a with the given class sidenav-contact__type, when clicked I then need to retrieve the data-contact-type value.
Now I could of course target this class in general, but when I click on the h5,p,figure or svg the script doesn't run due to none of those elements having the class sidenav-contact__type
The javascript I currently have is:
var myElements = document.getElementsByClassName('sidenav-contact__type');
for(var i = 0; i < myElements.length; i++){
myElements[i].addEventListener('click', function(){
console.log('here');
//get data-contact-type from div or a
});
}
Can a javascript guru please show me how I can register a click event on the children elements of the parent element that has the class sidenav-contact__types
note: has to be in javascript
This way you can retrieve the data contact-type attribute. Note the camelcase notation of contactType.
var myElements = document.getElementsByClassName('sidenav-contact__type');
for(var i = 0; i < myElements.length; i++){
myElements[i].addEventListener('click', function(){
console.log(this.dataset.contactType);
});
}
See here your working example: https://jsfiddle.net/skmqya0u/
try this it should work
var myElements = document.querySelectorAll(".sidenav-contact__type, .sidenav-contact__type *"); //select every class element and it's childs
for(var i in myElements){
myElements[i].addEventListener('click', function(){
console.log('here');
//get data-contact-type from div or a
});
}
So I have
<a href="1.html">
<img src = "image.jpg" class = "picture"/>
<div class="desc"><p>Brief Description</p></div>
</a>
<a href="2.html">
<img src = "image2.jpg" class = "picture"/>
<div class="desc"><p>Brief Description</p></div>
</a>
How do I cycle through the pictures and alter the div accordingly?
So far I have something like:
var pictures = $('.picture');
(var a = 0; a < pictures.size(); a++){
var description = (pictures.get(a)) (.siblings?)(.next?);
//Do what I want with the description
}
You can use Jquery .each() to loop through the elements. And .siblings() to get the sibling of that element.
$('.picture').each(function(){
var description = $(this).siblings('div. desc').text();
// Do what I want with the description
});
notice that .get(a) won't give you a jQuery set, but instead a plain object
https://api.jquery.com/jquery.get/
var pictures = $('.picture');
pictures.each(function() {
var description = $(this).next().html();
//Do what I want with the description
console.log(description);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="1.html">
<img src = "image.jpg" class = "picture"/>
<div class="desc"><p>Brief Description 1</p></div>
</a>
<a href="2.html">
<img src = "image2.jpg" class = "picture"/>
<div class="desc"><p>Brief Description 2</p></div>
</a>
How about selecting the description's <p> directly?
Like this:
$('.picture .desc p')....
You could use next.
$('.picture').each(function(idx, picture){
$(picture).next('.desc'); //this will select div.desc
});
The page will display an image's url text correctly. But I am not sure how to assign the message to the img 's src to display the image.
<DIV class="msgStyle1" id="message">Waiting for image</DIV>
<div class="imgStyle1" id="message">
<img src=whatneedtogohere /></div>
function displayText(text) {
console.log(text);
document.getElementById("message").innerHTML=text;
window.castReceiverManager.setApplicationState(text);
};
Fixed HTML (switched classes and IDs to make IDs unique) and added an image ID for simplicity:
<div id="msgStyle1" class="message">Waiting for image</div>
<div id="imgStyle1" class="message">
<img src="" id="image" />
</div>
JS:
document.getElementById('image').src = 'http://yourImagePathHere';
See it work here: http://jsfiddle.net/N3rCm/
First off, you shouldn't have multiple Id's on the page, it'll mess with your JS.
Next I would give your image a class if you can
//jquery example of what you would do
var imgSrc = 'http://wherever/youre/getting/this/from';
$('.myimageclass').attr('src', imgSrc);
//non jquery
var myImg = document.getElementsByClassName('myimageclass')[0]; //assuming it's the first one
//or if you can uniquely identify it
var myImg = document.getElementById('imgId');
myImg.src = imgSrc;