Now I have div created with javascript this divs have a background image with a different image, I need to add a class name to each div based on background image name, Is there a way to do this in javascript or jquery?
// adding divs to mapContainer
var mapCont = document.getElementById("mapContainer");
for (var i = 0; i < 20; i++) {
var child = document.createElement("div");
child.classList.add("logo-" + i);
mapCont.appendChild(child)
}
css
#mapContainer > div.logo-3 {
background-image: url(../images/car.png);
}
#mapContainer > div.logo-4 {
background-image: url(../images/bike.png);
}
#mapContainer > div.logo-5 {
background-image: url(../images/train.png);
}
How to add a class name to each div with the same background image name in javascript without the image extension so the divs have another class with the name of background image?
If i understood your question correctly, you can get the image path from the CSS class using the following code:
var body = document.getElementsByTagName('body')[0];
var elem = document.createElement("div");
elem.classList.add('logo-3');
body.appendChild(elem);
alert(getComputedStyle(elem).getPropertyValue('background-image'));
body.removeChild(elem);
It will alert the background-image style. Use the contents to add it to your classList. You might want to get the path with a regex.
Make sure to add the element to the DOM to get the properties, otherwise it will return null.
Related
change a div css class name of add to result and give it orange color on click
function changeclass(){
var name = document.getElementByClassName("add").name.className = "result",name.color = "orange"
Following your logic:
function changeClass(){
// get the element
var name = document.getElementsByClassName("add")[0];
// overwrite the element's existing classname
name.className = "result";
// set the element's style attribute with the desired attributes
name.style.color = "orange";
}
It would be better not to set the style attribute directly with JS. You are changing the class from .add to .result, so it makes more sense to use the class to set the styles:
.result {
color: orange;
}
I need to use JS to create a new element within specific nested classes in HTML. So in this example, I need to create a new span with the class of "paw-print" only where the "collies" class is nested within "dogs".
Here's what I have so far: https://jsfiddle.net/p50e228w/6/
The problem is that my current JS works on the first instance, but not on the other. I currently have document.getElementsByClassName set to "collies" but I need to target that class only when it's inside the parent "dogs" class.
What am I missing here?
var span = document.createElement("span");
span.className = "paw-print";
var wrap = document.getElementsByClassName("collies");
for(var i = 0; i < wrap.length; i++) {
wrap[i].appendChild(span);
}
I can use jQuery, but I've been using vanilla JS just because I'm such a noob and want to understand what my code is doing.
There are 2 issues with your code.
Positioning : The images are being given a absolute position, and they rest in the same position based on the page layout. So set relative positioning for the parent container.
CSS
.relative {
position: relative;
}
You need to append that to parent element which is collie here.
You can use querySelectorAll to find the nested relation ship that you are looking for.
var collies = document.querySelectorAll('.dogs .collies');
for (var i = 0; i < collies.length; i++) {
var span = document.createElement("span");
span.className = "paw-print";
collies[i].appendChild(span);
}
Fiddle
If you want to append to parent ( element with class 'dog')
$('.dogs .collies').each(function() // finds elements in the dom with parent element 'dog' and it's child element 'collies'
{
$(this) // 'this' would represent 'collies' element
.closest('.dogs') // .closest('.dogs') would get it's nearest occurence in the heirarchy ( basically it's parent )
.append($('<span/>', { class: 'paw-print'})); // create a dynamic span element and append to 'this'
});
If you want to append to child( element with class 'collies')
$('.dogs .collies').each(function()
{
$(this).append($('<span/>', { class: 'paw-print'}));
});
In addition to this, you also need to set position: relative as pointed out by Rob.
Example : https://jsfiddle.net/DinoMyte/1zxn8193/1/
Okay, I'm unsure how to word the question, but basically I want to repeat my div containers that have a class of "blocks" using only javascript, no HTML (other than the HTML needed to start a page). IF I were doing this using HTML the result should look exactly like this.
http://jsfiddle.net/nqZjB/1/
<div class = "blocks"> <!-- Repeats three times -->
However as I stated in the description I do not want to use any HTML, so here is my fiddle with javascript only.
How do I make div class blocks repeat three times as in my HTML example using only javascript? Of course in real life I would use HTML for this as javascript is unnecessary, but I want to do this in pure javascript so I can learn. Also as a sidenote if you have a better way as to how I should have worded the question, let me know.
Thanks (:
http://jsfiddle.net/TbCYH/1/
It's good you see the use of making a function of a re-occurring pattern.
Before posting it in StackOverflow, have you tried doing it yourself?
jsfiddle: http://jsfiddle.net/kychan/W7Jxu/
// we will use a container to place our blocks.
// fetch the element by id and store it in a variable.
var container = document.getElementById('container');
function block(mClass, html) {
//extra html you want to store.
return '<div class="' + mClass + '">' + html + '</div>';
}
// code that loops and makes the blocks.
// first part: creates var i
// second: condition, if 'i' is still smaller than three, then loop.
// third part: increment i by 1;
for (var i = 0; i < 3; i++) {
// append the result of function 'block()' to the innerHTML
// of the container.
container.innerHTML += block('block', 'data');
}
Edit: JS has changed a lot since the original post. If you do not require compatibility, use const, template literals, class and querySelector to make the code a bit cleaner. The following code has a Builder class and assumes there is a div with ID 'container':
// create class builder.
class Builder {
// create constructor, accept an element selector, i.e #container.
constructor(targetContainerSelector) {
// search element by given selector and store it as a property.
this.targetContainer = document.querySelector(targetContainerSelector);
}
// method to append to innerHtml of target container.
appendUsingInnerHtml(divAsHtml) {
this.targetContainer.innerHTML += divAsHtml;
}
// method to append to target container using DOM elements.
appendUsingDom(divAsDom) {
this.targetContainer.appendChild(divAsDom);
}
}
// constant to hold element selector.
const myTargetContainer = '#container';
// constant to set the class if required.
const myDivClass = 'my-class';
// constant to hold the instantiated Builder object.
const builder = new Builder(myTargetContainer);
// loop 3 times.
for (let i=0; i<3; i++) {
// call method to append to target container using innerHtml.
builder.appendUsingInnerHtml(`<div class="${myDivClass}}">innerhtml div text</div>`);
// OR.. build using DOM objects.
// create the div element.
const div = document.createElement('div');
// create text element, add some text to it and append it to created div.
div.appendChild(document.createTextNode('dom div text'));
// call method to append div DOM object to target container.
builder.appendUsingDom(div);
}
Please note: Every time something is added to the DOM, it forces the browser to reflow the DOM (computation of element's position and geometry).
Adding everything at once, improve speed, efficiency and performance of a code.
(ref: document.createDocumentFragment)
window.onload = Create();
function Create() {
// create the container
var mainContainer = document.createElement('div');
mainContainer.id = 'mainContainer';
// add all style in one go
mainContainer.setAttribute('style', 'witdht: 400px; height: 200px; border: 2px solid green; margin-left: 20px;');
var divBlocks1 = document.createElement('div');
divBlocks1.className = 'blocks';
divBlocks1.setAttribute('style', 'width: 100px; heigth: 100px; border: 1px solid black; margin-left: 20px; margin-top: 10px; floar: left;');
var divBlocks2 = divBlocks1.cloneNode(false); // copy/clone above div
var divBlocks3 = divBlocks1.cloneNode(false); // copy/clone above div
// everything is still in memory
mainContainer.appendChild(divBlocks1);
mainContainer.appendChild(divBlocks2);
mainContainer.appendChild(divBlocks3);
// now we append everything to the document
document.body.appendChild(mainContainer);
}
Good luck
:)
for(var d=0;d<10;d++){
var aDiv = document.createElement('div');
aDiv.className = "block";
document.getElementsByTagName('body')[0].appendChild(aDiv);
}
Rather than creating the elements before hand and then appending them to the main container, consider dynamically creating and appending them in a loop.
http://jsfiddle.net/TbCYH/6/
for(var i = 0; i < 3; i++) {
var divBlock = document.createElement("div");
divBlock.className = "blocks";
mainContainer.appendChild(divBlock);
}
In the above code snippet a div is being created and appended for each iteration of the loop (which is set to cease at 3).
Also if possible, always use CSS classes rather than modifying the styles for each div directly.
Using JavaScript, how to identify all images?
A straightforward approach is to traverse all DOM elements, and check: 1) if it is an <img />; 2) if its style includes background-image.
To get all img elements
var allImgs = document.getElementsByTagName('img');
To check if any element has a background-image, I might try something like this:
if (element.style['background-image'] != null) {/* your code */}
I'm not entirely sure about the 2nd one.
Get all images on the page:
function img_tag_find()
{
var img_collect = document.getElementsByTagName('img'); //collection of image
var img_collect_massiv = []; //array for image
for (var i = 0; i < img_collect.length; i++)
{
img_collect_massiv.push(img_collect[i].src); // push next image
}
return img_collect_massiv; // return array of image
}
Get element with style = 'background-image' - can be offered as Ramdas Nair
if (element.style['background-image'] != null) {/* your code */}
or try so (through all the elements, but not sure what's right do not have time to check)
function find_backgroundImage()
{
var object = document.getElementsByTagName('body');
var img_collect_massiv = []; //array for element page
for (var childItem in object.childNodes)
if (object.childNodes[childItem].style['background-image'] != null)
img_collect_massiv.push(object.childNodes[childItem]);
return img_collect_massiv; // return all element with style = 'background-image'
}
For cases when background image is defined in CCS, check whether an HTML element has a background image or not this way:
window.getComputedStyle(htmlElement).backgroundImage
The best way to gather all background images on a page would be to walk through all of active CSS to gather all of background-image references along with the style tag/class names to which the corresponding background images apply. Then only select HTML elements that match the corresponding styles all while making sure that they are not collapsed/hidden/display-none'd.
I am trying to create a div that can be attached to an element whenever user hover to the link
I have many links and my codes look like the following.
for loops to create many links
codes....
link.href='#';
link.innerHTML = 'test'
link.onmouseover = OnHover;
codes....
function OnHover(){
var position;
var div = document.createElement('div');
div.className='testdiv';
div.innerHTML = 'test';
position=$(div).position();
div.style.top = position['top'] + 15 + 'px';
$(this).prepend(div);
}
link element1
link element2
----
| | //add new div when hover link element2
----
link element2
link element3
my css
.testdiv{
position:absolute;
}
I want to add a new div everytime the user hover to my link and position on the left top of the element.
My code would position all the div on top instead of every element.
Are there anyway to do this? Thanks so much!
Without seeing your other JavaScript/markup I can make the following observations:
You need to set position:absolute on your new div before top will do anything.
You need to make sure link is non-position:static.
Non-dynamic styles like the above should be in your CSS, not JS.
Positioning absolutely means you shouldn't need to use $(div).position()
You're using a mix of jQuery and pure JavaScript which looks a little odd :)
JS
function OnHover() {
var position;
var div = $('<div></div>');
div.addClass('testdiv');
div.html('test');
div.css('top', 15);
$(this).prepend(div);
}
CSS
.testdiv {
position:absolute;
}
a.testanchor {
position:relative;
}