Getting the width of child element pure javascript - javascript

Html:
<div class="project-box">
<img src="img/ifix.jpg" class="thumbnail img-responsive">
<div class="hover-box">
<h2>TITLE</h2>
<p>Description of title</p>
</div>
</div>
javascipt:
window.onload = function(){
var project = document.getElementsByClassName('project-box');
img = project.getElementsByTagName('img');
alert(img.clientWidth);
};
I'm trying to get the img width and eventually the img height using pure JavaScript I know this is a lot easier with jQuery but I want to do it using only JavaScript.
EDIT:
I realized I was not specifying the array for the img and project
working js:
window.onload = function(){
var project = document.getElementsByClassName('project-box');
img = project[0].getElementsByTagName('img');
alert(img[0].offsetWidth);
};

Both getElementsByClassName and getElementsByTagName returns an array of objects, so you need to access the actual element by its index then call its methods/properties
window.onload = function () {
var project = document.getElementsByClassName('project-box')[0];
var img = project.getElementsByTagName('img')[0];
alert(img.clientWidth);
};
Demo: Fiddle

I believe project.getElementsByTagName('img'); is returning an array, even if it only has one object.
Try something like
window.onload = function(){
var project = document.getElementsByClassName('project-box');
img = project.getElementsByTagName('img');
alert(img.pop().width); //This should remove the element from the array and then call width
};

Try this one:
alert(img.clientWidth);

The reason this is not working is because .getElementsByClassName() and .getElementsByTagName() both wrap elements inside an [object HTMLContainer], you need to select the first element from each of these objects.
This code should work:
window.onload = function()
{
var project = document.getElementsByClassName('project-box');
img = project[0].getElementsByTagName('img');
console.log(img[0].clientWidth);
};

Related

Create figure using function javaScript function createElement(tagName)

I need to create a new figure at runtime on my web app. I am using javascript and html/css.
The element that i got to create is the follow:
<figure id = "myImage" class="ball" >
<span class="shadow">
</span>
</figure>
I have tried some tag names and the "ball" isn't created.
The following code is an example(not working) what is the problem?
var generatedBall = document.createElement("FIGURE");
generatedBall.class = 'ball';
generatedBall.style.background = 'yellow';
document.body.appendChild(generatedBall);
Thanks for help.
It's working for me, see my fiddle.
You just have to give it height;
var generatedBall = document.createElement("figure");
generatedBall.classList.add('ball'); //Edited this
generatedBall.style.background = 'yellow';
generatedBall.style.height = '100px'; //Added bit
document.body.appendChild(generatedBall);
See the exact output on this page See Here
var innerSpan = document.createElement('span');
innerSpan.classList.add('shadow');
var generatedBall = document.createElement('figure');
generatedBall.setAttribute("id","myImage")
generatedBall.classList.add('ball');
document.body.appendChild(generatedBall);
generatedBall.appendChild(innerSpan);
The Element does not have a class property. Instead, you can add and remove classes using classList. So your example would become:
var generatedBall = document.createElement('figure');
generatedBall.classList.add('ball');
generatedBall.style.background = 'yellow';
document.body.appendChild(generatedBall);

Check if an element has a background-image with pure JS?

What is the correct way to check if a particular element has a background-image associated with it, in pure Javascript?
Right now I have this:
var elementComputedStyle = window.getComputedStyle(element);
var hasBGImage = elementComputedStyle.getPropertyValue('background-image') !== 'none'
What you have works, but there are alternate ways of finding the property that you might find easier. I don't believe there is a single 'correct' way to do it, however.
Just javascript:
var hasBGImage = element.style.backgroundImage !== '';
Using jQuery:
var hasBGImage = $(element).css('background-image') !== 'none';
Make sure you declare the background image "inline", otherwise .style.backgroundImage won't work.
<script>
window.onload=function() {
var bg = document.getElementById('el').style.backgroundImage.length!=0;
alert(bg);
}
</script>
<div id='el' style="background-image: url('a.jpg');"></div>
If you can use inline CSS, that's the way. If, for some reason, you can't use that, let me know, I'll try to find out something else :)
I used this code in last one project and works perfect
// Check all background images exists
var imageURLs = $('.image-container ');
imageURLs.each(function(index, element){
var imageURL = $(element).css('background-image').replace('url("', '').replace('")', '');
var img = new Image();
img.onerror = function() { $(element).css('background-image','url(/build/images/missing-image.svg)'); };
img.src = imageURL;
});

Target child of children with .each() in jQuery

I’m iterating through the elements and grabbing the src attribute of the child of that element. I have this HTML code:
<noscript data-alt="super awesome">
<img src="http://farm9.staticflickr.com/8235/8585847956_39864361e3.jpg" alt="something" />
</noscript>
<noscript data-alt="super awesome">
<img src="http://farm9.staticflickr.com/8235/8585847956_39864361e3.jpg" alt="something" />
</noscript>
and jQuery:
$('body').children().each(function() {
var noscriptTag = $(this)[0];
var imgAlt = noscriptTag.getAttribute("data-alt");
var img_src = noscriptTag.find('img');
var img_regular = img_src.getAttribute("src");
console.log(img_regular);
});
But I’m getting this error:
Uncaught TypeError: Object #<HTMLElement> has no method 'find'
I also tried various other combinations (like $(this).find('img');) without making it work.
Here’s the demo: http://jsfiddle.net/LjWhw/
How do I target the img tag of that element? Thanks!
UPDATE: You can’t target elements which are inside <noscript> with JavaScript.
You are trying to call find jQuery function on DOM object, Use jQuery object instead of DOM javascript object to call find on it.
Change
var noscriptTag = $(this)[0];
To
var noscriptTag = $(this);
Edit: You will also need to change the code accordingly e.g. img_src.getAttribute("src"); to img_src[0].getAttribute("src"); or img_src.attr("src");
I would suggest you to do it this way:
$('body').children().each(function() {
var noscriptTag = $(this).find('noscript').first();
//---------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-----this way
var imgAlt = noscriptTag.getAttribute("data-alt");
var img_src = noscriptTag.find('img');
var img_regular = img_src.attr("src");
console.log(img_regular);
});
try this
http://jsfiddle.net/UQJsy/1/
$('noscript').each(function () {
var noscriptTag = $(this);
var imgAlt = noscriptTag.attr("data-alt");
var img_src = noscriptTag.children('img');
var img_regular = img_src.attr("src");
alert(imgAlt);
});

move node from second to first

Just want a function that move second node to be a first node.But it not working, any suggestion?
var node = document.getElementById("ir");
var cx = node.childNodes[1];
function der(){
node.insertBefore(cx,node.firstChild);
}
fullcode:
<div id="ir">
<p id="ie">test</p>
<img src="test.gif">
</div>
<script type="text/Javascript">
var node = document.getElementById("ir");
img.setAttribute("onclick","der()");
var cx = node.childNodes[1];
function der(){
node.insertBefore(cx,node.previousSibling);
}
http://jsfiddle.net/joeframbach/JSZPy/
The issue with the html in that fiddle is the spaces. childNodes[0] matches the first set of spaces, and childNodes[1] matches the first element. Perhaps this is your issue.
<div id="ir">
<p>First</p>
<p>Second</p>
</div>
var node = document.getElementById("ir");
var first = node.childNodes[1];
var second = node.childNodes[3];
node.insertBefore(second,first);
I'm a bit slow today, but I think your use of previousSibling is wrong. I think it should relate to the child node cx not the parent node .. so you should be using cx.previousSibling not node.previousSibling - I've edited mt previous example to remove my original dumb response ... try this ...
<div id="ir">
<p id="ie">test</p>
<img src="test.gif">
</div>
<script type="text/Javascript">
var node = document.getElementById("ir");
img.setAttribute("onclick","der()");
var cx = node.childNodes[1];
function der(){
node.insertBefore(cx,cx.previousSibling);
}
Two Days Later Edit !!! ....
Of course the example I gave above will not swap the P element and the image because the image's true previousSibling is a newline character between the /P tag closure and the image. More importantly from a coding perspective, it won't work because there isn't an object called 'img' defined anywhere ... so I offer this as a working alternative :
<script>
function swapDivs(obj) {
if(obj.previousSibling){ // if it's null, then it's already the first element //
obj.parentNode.insertBefore(obj, obj.previousSibling);
}
}
</script>
<div id="ir">
<p id="ie">test</p><img src="http://i2.ifrm.com/4639/142/emo/drool.gif" onclick="swapDivs(this);" />
</div>
It doesn't address the newline issue, I just reformatted the HTML.
However, it does resolve the img issue, and provides a generic way of adding the function to any clickable DOM object without having to customise the function.
I'll leave it to you to work out how to get over the problem with the newline/whitespace sibling, but it shouldn't be to difficult. Here's the fiddle to play with if you want to test your attempts ... http://jsfiddle.net/radiotrib/ps9XZ/
You've got an answer but i recommend doing something like:
var node = document.getElementById("ir");
var childs = node.getElementsByTagName("div");
var cx = childs[1];
function der()
{
node.removeChild(cx);
node.insertBefore(cx, childs[0]);
}
der();
I advise you not to put spaces or breaklines when working with childnodes, because they are considering like child of text type. I hope this code will help you:
Javascript code:
function change(){
var parent = document.getElementById("ir");
var img = parent.childNodes[1];
parent.removeChild(img);
parent.insertBefore(img, parent.firstChild);
}
HTML code:
<div id="ir"><p id="ie">test</p><img src="test.gif"></div>
<button onclick="change()">Change</button>

javascript document.getElementById not working

Following is my javascript program. I am trying to get all child tags of parent div tag but when I am running the program document.getElementById('abc') returning null.
function init(){
// currentDiv = document.getElementById("intro");
alert("working");
count = 0;
divs = document.getElementById('abc').getElementsByTagName("div");
alert("HI " + divs)
currentDiv = divs[count];
nextDiv = divs[count + 1]
count = count + 1;
}
window.onload = init();
Following is my div tag definitions:
<div id='abc'>
<div></div>
</div>
thanks.
The problem is in this line:
window.onload = init();
You are running init and setting the return value as the value of window.onload. My guess is that the code is being executed before the DOM is ready, i.e. before the divs exist.
Try this instead:
window.onload = init;
I suggest you start using jQuery instead, then you have much more powerful tools for this kind of DOM search/traversing
<body onload="init()">
<div id='abc'>
<div></div>
</div>
</body>
this probably solves your problem

Categories

Resources