Showing posts with label JavaScript DOM Manipulation. Show all posts
Showing posts with label JavaScript DOM Manipulation. Show all posts

Tuesday, December 6, 2016

JavaScript DOM Manipulation - jQuery - CSS - Q&A

Question:

Write code that shows how to give a class to all X tag elements in an HTML page using CSS | JS | JQUERY

Answer

// CSS

div{

    background: rgba(0, 180, 0, .3);

    width: 150px;

    height: 150px; }


// JavaScript

var divs = document.getElementsByTagName('DIV');

for (i in divs){

    divs[i].className = "newDivClass";

};


// jQuery

var divs = $('DIV');

$.each(divs, function(index){

    divs[index].className = "newDivClass"

});


JavaScript - document.ready() - Q&A

Question:

What is the difference between these two lines of code?


$(document).ready(function() {}); // first line

$(function() {}); // second line


Answer


The two lines do exactly the same. The second line is just a shorten way for the first line.
 Both set the method for document ready.

JavaScript - jQuery - DOM Manipulation - Q&A

Question:

Output all elements count and print them to the page in the following format :








Answer

var all = $('*');
console.log( all.length );
var elements = [];
for (var i = 0;  i < all.length;  i++){
    if (!elements[$(all[i]).prop('tagName')])
        elements[$(all[i]).prop('tagName')] = 1;
    else
        elements[$(all[i]).prop('tagName')]++;
};
console.log(elements);

JavaScript - jQuery selectors - Q&A

Question:

Give examples for the following jQuery selectors:
1) Select all paragraphs with the class “yellow”
2) Select all <div> tags by name “green”

Answer